Fragment 详解与使用

来源:互联网 发布:远程端口修改 编辑:程序博客网 时间:2024/05/21 03:56

Fragment又名碎片。因手机和平板的屏幕尺寸呢和分辨率越来越大,在android3.0之后出现了Fragment 

先开看一下Fragment的生命周期:


可以看到,比Activity的生命周期多了几个方法。


OK,还是来讲解一下主要的用法:

第一种用法:将Fragment嵌入到xml布局中使用

一个Activity里面存放着两个Fragment(类似于新闻)

先来看看放在左边的Fragment(用来做菜单),这个Fragment的布局文件里面就是一个ListView,在此处是继承的ListFragment,一般情况下是继承Fragment即可

public class TitlesFragment extends ListFragment {     private String[] array;         @Override     public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);                   // 设置List          array = new String[] {"动作游戏", "恋爱养成", "角色扮演", "策略游戏", "即时战略", "体育竞技", "战棋类"};          List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();          for (int i = 0 ; i < array.length ; i++) {               Map<String, Object> map = new HashMap<String, Object>();               map.put("title", array[i]);               data.add(map);          }          String[] from = new String[] { "title" };          int[] to = new int[] { android.R.id.text1 };          ListAdapter adapter = new SimpleAdapter(getActivity(), data, android.R.layout.simple_list_item_1, from, to);          setListAdapter(adapter);     }         @Override     public void onListItemClick(ListView l, View v, int position, long id) {          super.onListItemClick(l, v, position, id);                   String title = array[position];                   // 创建Bundle,传参数          Bundle bundle = new Bundle();          bundle.putString("title", title);                   // 将Bundle传输到Fragment          DetailsFragment fragment = new DetailsFragment();          fragment.setArguments(bundle);                   getFragmentManager().beginTransaction().replace(R.id.fl_details, fragment).commit();     }}


右边的Fragment

<span style="font-size:14px;">public class DetailsFragment extends Fragment {     private static final String TAG = "DetailsFragment";         private String title;         @Override     public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);                   title = getArguments().getString("title");                   Log.i(TAG, "onCreate");     }         /**     * 绑定布局文件     */     @SuppressWarnings("static-access")     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          View view = inflater.from(getActivity()).inflate(R.layout.fragment_details, container, false);                   TextView txTitle = (TextView) view.findViewById(R.id.tx_title);          txTitle.setText(title);                   Log.i(TAG, "onCreateView");                   return view;     }    }</span><span style="color:#ff4635;font-size: 21px;"></span>

最后主类Activity的布局文件:

<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:divider="#ccc"    android:orientation="horizontal"    android:showDividers="middle"    tools:ignore="DisableBaselineAlignment" >    <fragment        android:id="@+id/fg_titles"        android:name="com.qf.teach.day12.ui.fragment.fragment.TitlesFragment"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="3" />    <FrameLayout        android:id="@+id/fl_details"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="1" /></LinearLayout>


下面来介绍第二种Fragment的用法:


Activity中你可以通过getFragmentManager()来获得Fragment对象,然后通过FragmentManager对象的beginFragmentTransaction()方法来获得FragmentTransaction对象。通过它的add()方法来添加一个Fragment到当前的Activity中。

一个FragmentTransaction对象可以执行多个增删修的方法,如果你想把这些修改提交到Activity上,必须在最后调用一下这个对象的commit()方法。例子:

Activity继承FragmentActivity,Activity的布局文件为:


接着来看一下Activity的代码:



由于不是定义在XML布局中的,所有可以转型删除和修改的操作。

如果替换或者删除一个Fragment然后让用户可以导航到上一个Fragment,你必须在调用commit()方法之前调用addToBackStack()方法添加到回退栈。如果你把这个Fragment添加到了回退栈,在提交之后这个Fragment是会被Stop而不是Destroyed。如果用户导航到这个Fragment,这个Fragment会被Restart而不是重新创建。如果你没有把它添加到回退栈,则在删除或者替换的时候它将被Destroyed。例子:


与其他Fragment的交互

两个单独的Fragment之间是不应该进行通信的。应该使用他们所存在的Activity作为沟通的纽带。

为了实现两个Fragment的交互,您可以在Fragment中定义一个接口,然后再这个接口中定义一个方法,在FragmentonAttach()方法中调用这个接口中的方法。然后让Activity实现这个方法来完成ActivityFragment之间的通信。例子:

定义接口并调用方法:



实现接口,在这个方法中可以进行与其他Fragment的数据的交互:



可以通过FragmentManagerfindFragmentById()来查找一个Fragment








0 0
原创粉丝点击