1 Fragment的产生与介绍
》
Fragment,也就是碎片,本意是为了适配大屏幕的安卓设备而生的。运行Android的设备繁多,屏幕大小更是多种多样。针对不同屏幕尺寸,通常情况下,开发者都是先针对手机开发一套源代码,然后拷贝一份,修改布局以适应大屏幕设备,或平板等。为了决解这样的麻烦,Google推出了Fragment。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。
2 Fragment的生命周期:
可以看到Fragment比Activity多了几个额外的生命周期回调方法:
onAttach(Activity)
当Fragment与Activity发生关联时调用。
onCreateView(LayoutInflater, ViewGroup,Bundle)
创建该Fragment的视图
onActivityCreated(Bundle)
当Activity的onCreate方法返回时调用
onDestoryView()
与onCreateView想对应,当该Fragment的视图被移除时调用
onDetach()
与onAttach相对应,当Fragment与Activity关联被取消时调用
注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现。
3 静态使用Fragment:
1、继承Fragment,重写onCreateView决定Fragemnt的布局,新建两个FragmentOne,FragmentTwo类
2.添加XML布局控件:
public class FragmentOne extends Fragment {
private TextView mTextView;
// 相当于Activity的的onCreate
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// 让碎片加载一个布局 参数 :1 布局 2 container 3固定 false
View view = inflater.inflate(R.layout.fragment_one,container,false);
mTextView = (TextView) view.findViewById(R.id.text);
mTextView.setOnClickListener(new View.OnClickListener() {