Android碎片 -- Fragment

来源:互联网 发布:淘宝买家注册 编辑:程序博客网 时间:2024/05/17 13:12
 一, Fragment是什么?
是Android 3.0后出现,  API 11以上, 是Activity的一部分
Fragment 可以显示内容, 可以和用户交换
Fragment 的作用:  提高代码重用性  和 用户体验 ,可以对Activity的组件进行分组和模块化的管理
Fragment 有自己的生命周期和接收处理用户的事件  , 可以添加  移除   替换
注意:
1, Fragment 必须要显示在Activity中
2, 一个Activity可以包含多个Fragment ; 一个Fragment 可以被多个Actvity使用

   二, 如何创建Fragment?
1, 定义一个类, 继承Fragment <app>
2, 重写父类的生命周期方法: onCreateView()
   三, Fragment的显示方式?
1, 静态方式显示(固定内容 不需要接收数据)
1.1   在Activity 要显示的布局页面中通过标签引入<fragment/>
1.2   在标签中必须要指定id  , 用来标识Fragment的唯一性
1.3   在标签中必须要指定name, 指定要显示的是那个Fragment
2, 动态方式显示(传值)
2.1    在要显示的页面中, 通过布局容器占位
2.2    在Activity中
1, 得到Fragment的管理器对象
2, 通过管理器对象  开启Fragment的事务处理
3, 实例化要显示的Fragment
4, 动态显示Fragment
5, 提交事务
方法:  
替换  replace
移除  remove
添加  add 
隐藏  hide
显示  show
transaction.addToBackStack(null);//将当前的Fragment加入到回退栈中

  四, Activity向Fragment传值
1, Activity中
Bundle bundle = new Bundle();
bundle.putString(key,value);
fragment.setArguments(bundle);
2, Fragment中
Bundle bundle = getArguments();
String key = bundle.getString(key);
   五, Fragment向Activity传值(接口回调)
1, Fragment中
public void getEditText(CallBack callBack)
{
String msg = et.getText().toString().trim();

callBack.sendResult(msg);

}
//回调接口
public interface CallBack
{
public void sendResult(String result);
}

2, Activity中
fragment.getEditText(new CallBack() {
@Override
public void sendResult(String result) {
tv.setText(result);
}
});


   六, Fragment向Fragment传值
         1, LeftFragment  :
//传值
Bundle args = new Bundle();
args.putString("fileName", data.get(position));
fragment.setArguments(args);
2, RightFragment:
//取值
   七, Fragment的生命周期  11个

1, 初始化阶段   4个
onAttach()        与归属Activity建立连接
onCreate() 初始化Fragment
onCreateView()初始化Fragment中显示的UI布局
onActivityCreated()     归属Activity的onCreate()方法执行完成
2, 显示/隐藏   4个
onStart() 显示Fragment
onResume() 获得用户焦点
onPause() 失去用户焦点
onStop() 关闭Fragment
3, 销毁阶段    3个
onDestroyView()销毁Fragment显示的UI布局
onDestroy() 销毁Fragment
onDetach() 与归属Activity断开连接
    静态方式:
显示:  F:onAttach -- F:onCreate -- F:onCreateView -- M:onCreate -- F:onActivityCreated  -- M:onStar -- F:onStrar -- M:onResume -- F:onResume
退出:  F:onPause  -- M:onPause -- F:onStop -- M:onStop -- F:onDestroyView  -- F:onDestroy -- F:ondetach -- M:onDestroy
   动态方式:
显示: M:onCrate -- F:onAttach -- F:onCreate -- F:onCreateView --F:onActivityCreated  -- M:onStar -- F:onStrar -- M:onResume -- F:onResume

退出:  F:onPause  -- M:onPause -- F:onStop -- M:onStop -- F:onDestroyView  -- F:onDestroy -- F:ondetach -- M:onDestroy

静态添加Fragment的方法实例:

<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"    tools:context=".MainActivity" >    <fragment        android:id="@+id/left"        android:name="com.example.day44fragment.Fragmentleft"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" />    <fragment        android:id="@+id/right"        android:name="com.example.day44fragment.Fragmentright"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="2" /></LinearLayout>
public class Fragmentleft extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView v = inflater.inflate(R.layout.left, null);return v;}}

public class Fragmentright extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View v = inflater.inflate(R.layout.right, null);return v;}}

动态添加Fragment实例:

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void add(View v) {// 得到fragment管理器对象FragmentManager manager = getFragmentManager();// 通过管理器打开fragment实物FragmentTransaction transaction = manager.beginTransaction();// 实例化显示fragmentHelloFragment helloFragment = new HelloFragment();// 动态显示fragment// transaction.add(R.id.layout_id, helloFragment);transaction.replace(R.id.layout_id, helloFragment);// 提交事务transaction.commit();}}
<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"    tools:context=".MainActivity" >    <Button         android:id="@+id/button_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="添加Fragment"        android:onClick="add"/>    <!-- 布局容器的占位 -->    <LinearLayout        android:layout_below="@id/button_id"        android:layout_width="wrap_content"        android:orientation="horizontal"        android:id="@+id/layout_id"        android:layout_height="wrap_content" /></RelativeLayout>

public class HelloFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView v = inflater.inflate(R.layout.hello, null);return v;}}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView         android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/tv"        android:textSize="26sp"        android:text="我是动态加载的fragment"/></LinearLayout>

V4 包中Fragment用法:
 app包  兼容的最低版本是 3.0
 V4包    兼容的最低版本是1.6
创建方式
V4包中使用Fragment
1, 定义一个类, 继承Fragment(V4)
2, 归属Activity 继承FragmentActivity(V4)
3, 动态显示   管理器对象:  FragmentManager manager = getSupportFragmentMessag(); (V4)
4, 动态显示    事务:  FragmentTransaction transaction  = manager.beginTransaction();(V4

 ListFragment的用法
方式一:
1, 定义一个类, 继承ListFragment
2, 在布局中的ListView控件的ID , 必须为: android:id = "@id/android:list"
3, 在onCrateView之前的生命周期方法中  初始化数据源和适配器, 在它之后的生命周期方法中 设置适配器
4, 设置适配器:  setListAdapter(adapter)
5, 设置点击事件监听器:  重写父类的方法:  onListItemClick()
6, 在onActivityCreated方法中得到ListView控件:  getListView()
方法二:
1, 定义一个类, 继承ListFragment
2, 在onCrateView之前的生命周期方法中  初始化数据源和适配器
3, 在onCrateView之后的生命周期方法中   设置适配器
4, 监听  重写父类的方法  onListItemClick()
5,在onActivityCreated方法中得到ListView控件:  getListView()

实例:

//1, 定义一个类, 继承ListFragmentpublic class MyFragment extends ListFragment {private ListView lv;private List<String> data;// 数据源private ArrayAdapter<String> adapter;// 适配器@Overridepublic void onAttach(Activity activity) {// TODO 初始化数据源和适配器super.onAttach(activity);data = new ArrayList<String>();for (int i = 0; i < 20; i++) {data.add("Item ---- " + i);}adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, data);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// 为Fragment设置要显示的UI页面View view = inflater.inflate(R.layout.my_fragment, container, false);return view;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {// TODO 设置适配器super.onActivityCreated(savedInstanceState);// 3, 设置适配器setListAdapter(adapter);//5, 得到当前的ListView对象lv = getListView();lv.setOnItemLongClickListener(new OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {Toast.makeText(getActivity(), "你长按了 :  " + data.get(position),Toast.LENGTH_SHORT).show();return true;}});}// 4, 点击事件@Overridepublic void onListItemClick(ListView l, View v, int position, long id) {// TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id);Toast.makeText(getActivity(), "你点击了 :  " + data.get(position),Toast.LENGTH_SHORT).show();}}
<!-- 2, id 必须为: @id/android:list -->    <ListView         android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@id/android:list"        />
或者:

//1, 定义一个类, 继承ListFragmentpublic class LeftFragment extends ListFragment {private List<String> data;private ArrayAdapter<String> adapter;//2, 在onCreateView 之前的生命周期方法中 初始化  数据源和适配器@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);data = new ArrayList<String>();for(int i=0;i<30;i++){data.add("阿童木  -- >" + i);}adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data);}//3, 在onCreateView之后的生命周期方法中, 设置适配器  , 得到ListView控件@Overridepublic void onActivityCreated(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onActivityCreated(savedInstanceState);setListAdapter(adapter);ListView lv = getListView();}//4, 重写父类的方法, 完成ListView的点击事件  (父类值提供了点击监听器 , 其他事件通过得到控件直接设置)@Overridepublic void onListItemClick(ListView l, View v, int position, long id) {super.onListItemClick(l, v, position, id);Toast.makeText(getActivity(),data.get(position), Toast.LENGTH_SHORT).show();}}





  
0 1
原创粉丝点击