创建Fragment
-
Fragment的创建过程非常简单,与Activity类似,创建Fragment时必须创建一个类继承自Fragment。一个Activity中可以包含多个Fragment,一个Fragment也可以在多个Activity中使用,如果在Activity中有多个相同的业务模块,则可以复用Fragment。
public class NewsListFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
return v;
}
}
inflate方法的三个参数含义:
第一个参数表示Fragment对应的布局资源ID
第二个参数表示存放Fragment布局的ViewGroup
第三个参数表示是否在创建Fragment的布局时附加到ViewGroup上。
在Activity中添加Fragment
在Activity中使用Fragment时,可以通过两种方式将Fragment添加到Activity中,一种是通过布局文件添加,一种是通过代码动态添加。
1)通过布局文件添加Fragment
使用Fragment时只需要将Fragment作为一个控件在Activity的布局文件中进行引用即可。
<fragment
android:name="cn.itcast.NewsListFragment“
android:id="@+id/newslist"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
2)通过代码动态添加Fragment
除了可以在布局文件中添加Fragment之外,还可以在Activity中通过代码动态添加Fragment,这种方式更加的灵活。
在Activity中动态添加Fragment的步骤:
a)创建一个Fragment的实例对象。
b)获取FragmentManager(Fragment管理器)的实例。
c)开启FragmentTransaction(事务)。
d)向Activity的布局容器(一般为FrameLayout)中添加Fragment。
e)通过commit()方法提交事务。
例如:
NewsListFragment fragment = new NewsListFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction beginTransaction = fm.beginTransaction();
beginTransaction.replace(R.id.ll,fragment);
beginTransaction.commit();