关于Fragment的方方面面
android,Fragment2016-08-02
简介
Fragment相当于是一种特殊的Activity,它需要被嵌套到Activity上面才能起作用,那么对于大屏设备(如:平板)就就可以考虑在一个Activity上面放置多个Fragment,这样可以充分利用屏幕面积,而且也可以更方便用户进行交互操作,当然在手机上面也可以方便的使用它,有了Fragment,我们的APP可以针对平板或是手机做不同的适配。Fragment是在Android3.0(API level 11)版本引入的,如果你使用的是之前的系统,需要先导入android-support-v4的jar包。
先看下Fragment的生命周期吧:
可以看出跟Activity很像,只是多了几个方法,单独说明一下:
onAttach()public class MyFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
} 在activity_main.xml里面<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/id_fragment_title"
android:name="com.example.wdong.fragmentdemo.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout> 然后是动态加载:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout> 在MainActivity的onCreate()里面MyFragment fragment = new MyFragment(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment).commit();
在使用Fragment时,常用的api有以下这些:
一、getFragmentManager()获取FragmentManager。FragmentTwo two = new FragmentTwo(); FragmentManager fm = getFragmentManager(); FragmentTransaction tx = fm.beginTransaction(); tx.replace(R.id.id_content, two, "two"); //tx.hide(this); //tx.add(R.id.id_content , two, "two"); //这种方式的话FragmentOne的视图层就不会被销毁了 tx.addToBackStack(null); tx.commit();这样就跳转到了FragmentTwo,由于我们加了tx.addToBackStack(null),所以再按back键,就会回到FragmentOne。
View listView = getActivity().findViewById(R.id.list);同样地,activity可以通过从FragmentManager获得一个到Fragment的引用来调用fragment中的方法,使用findFragmentById() 或 findFragmentByTag()。
MyFragment fragment =(MyFragment) getFragmentManager().findFragmentById(R.id.my_fragment);