1.如何动态加载Fragment?
- 在Activity的布局文件中添加存放fragment的ViewGroup:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal" >
- </LinearLayout>
- 生成Fragment的布局:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#00FF00"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/lblFragment1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="This is fragment #1"
- android:textColor="#000000"
- android:textSize="25sp" />
- </LinearLayout>
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // ---Inflate the layout for this fragment---
- return inflater.inflate(R.layout.fragment1, container, false);
- }
- }
- 在Activity中动态添加:
- public class FragmentsActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- FragmentManager fragmentManager = getFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager
- .beginTransaction();
- // ---get the current display info---
- WindowManager wm = getWindowManager();
- Display d = wm.getDefaultDisplay();
- // ---landscape mode---
- Fragment1 fragment1 = new Fragment1();
- // android.R.id.content refers to the content
- // view of the activity
- fragmentTransaction.replace(android.R.id.content, fragment1);
- // ---add to the back stack---
- fragmentTransaction.addToBackStack(null);
- fragmentTransaction.commit();
- }
- }
2.fragment与Activity,fragment与fragment之间如何通信?
调用FragmentManager的findFragmentById()方法,可以在活动中得到相应碎片的实例,然后就能轻松地调用碎片里的方法了。
- Activty调用Fragment:
-
RightFragment rightFragment = (RightFragment) getFragmentManager().findFragmentById(R.id.right_fragment);
-
-
Fragement调用Activity:
-
MainActivity activity = (MainActivity) getActivity();
-
- Fragment与Fragment:通过(1)(2)
3.如何同一个activity在平板和手机显示不同的布局?
使用限定符:在res目录下新建layout-large文件夹,在这个文件夹放双页模式(程序会在左侧的面板上显示一个包含子项的列表,在右侧的面板上显示内容)的布局.Android中一些常见的限定符可以参考下表。
屏幕特征 |
限定符 |
描述 |
大小 |
small |
提供给小屏幕设备的资源 |
normal |
提供给中等屏幕设备的资源 | |
large |
提供给大屏幕设备的资源 | |
xlarge |
提供给超大屏幕设备的资源 | |
分辨率 |
ldpi |
提供给低分辨率设备的资源(120dpi以下) |
mdpi |
提供给中等分辨率设备的资源(120dpi到160dpi) | |
hdpi |
提供给高分辨率设备的资源(160dpi到240dpi) | |
xhdpi |
提供给超高分辨率设备的资源(240dpi到320dpi) | |
方向 |
land |
提供给横屏设备的资源 |
port |
提供给竖屏设备的资源 |
使用最小宽度限定符:小宽度限定符允许我们对屏幕的宽度指定一个最小指(以dp为单位),然后以这个最小值为临界点,屏幕宽度大于这个值的设备就加载一个布局,屏幕宽度小于这个值的设备就加载另一个布局。如:在res目录下新建layout-sw600dp文件夹,则当程序运行在屏幕宽度大于600dp的设备上时,会加载layout-sw600dp/ activity_main布局,当程序运行在屏幕宽度小于600dp的设备上时,则仍然加载默认的layout/activity_main布局。