android学习之路Android知识Android开发

【Android】Fragment初探索

2016-07-08  本文已影响141人  紫豪

1. Fragment的产生

Android在Android3.0中开始引入了Fragment(碎片),其目的是让界面可以在平板上更好地展示、提高界面的灵活性。
  Fragment必须被写成可重用的模块。因为Fragment有自己的layout,自己进行事件响应,拥有自己的生命周期和行为,所以你可以在多个Activity中包含同一个Fragment的不同实例。这对于让你的界面在不同的屏幕尺寸下都能给用户完美的体验尤其重要。


fragment.png

2. Fragment的生命周期、与Activity的对应关系

Fragment不能独立存在,它必须嵌入到Activity中,而且Fragment的生命周期直接受所在的Activity的影响。例如:当Activity暂停时,它拥有的所有的Fragment们都暂停了,当Activity销毁时,它拥有的所有Fragment们都被销毁。然而,当Activity运行时(在onResume()之后,onPause()之前),你可以单独地操作每个Fragment,比如添加或删除它们。当你在执行上述针对Fragment的事务时,你可以将事务添加到一个棧中,这个栈被Activity管理,栈中的每一条都是一个Fragment的一次事务。有了这个栈,就可以反向执行Fragment的事务,这样就可以在Fragment级支持“返回”键(向后导航)。


3. Fragmet的优点


4. Fragment的使用

public class LoginFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup  container,Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            // 设置对应布局
            View view = inflater.inflate(R.layout.fragment_login, container, false);
            return view;
        }
}
<LinearLayout 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"
  android:orientation="vertical" >

     <fragment
       android:id="@+id/login_fragment"
        android:name="com.example.test.LoginFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

<LinearLayout 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"
 android:orientation="vertical" >
 
 <FrameLayout
  android:id="@+id/fragment_content"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />
</LinearLayout>
- 在Activity对Fragment进行管理
 // 1.获取碎片管理器
 FragmentManager fragment = getFragmentManager();
 // 2.开启Fragment事务
 FragmentTransaction transaction = fragment.beginTransaction();
 // 3.指定事务行为
 transaction.replace(R.id.fragment_content, mLoginFragment);
 // 4.提交事务开始执行
 transaction.commit();
```


上一篇 下一篇

猜你喜欢

热点阅读