[关闭]
@ZeroGeek 2015-08-26T06:23:31.000000Z 字数 2241 阅读 596

Fragment 学习小结

android


参考 : http://developer.android.com/guide/components/fragments.html

一 概述

Android 3.0(API level 11)加入,为了使界面更灵活,可复用,动态生成。

二 要点:

三 使用方法

1. 必须实现的方法

2. 基本的fragment类型

3. 添加Fragment到Activity

3.1 带界面

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <fragment android:name="com.example.news.ArticleListFragment"
  7. android:id="@+id/list"
  8. android:layout_weight="1"
  9. android:layout_width="0dp"
  10. android:layout_height="match_parent" />
  11. <fragment android:name="com.example.news.ArticleReaderFragment"
  12. android:id="@+id/viewer"
  13. android:layout_weight="2"
  14. android:layout_width="0dp"
  15. android:layout_height="match_parent" />
  16. </LinearLayout>
  1. FragmentManager fragmentManager = getFragmentManager()
  2. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  1. ExampleFragment fragment = new ExampleFragment();
  2. fragmentTransaction.add(R.id.fragment_container, fragment);
  3. fragmentTransaction.commit();

3.2 不带界面

修改如下方法即可:

add(Fragment, String)

设置Tag 来给其提供唯一标识(比id好)

使用方法:findFragmentByTag()

4. 管理Fragments

通过FragmentManager,FragmentTransaction
- add()
- remove()
- replace()

commit()之前,可以setTransition(),使Fragment 变化带有动画效果。

5. 替换Fragment的事项。

四 与Activity交互

常用方法

创建回调函数

  1. public static class FragmentA extends ListFragment {
  2. ...
  3. // Container Activity must implement this interface
  4. public interface OnArticleSelectedListener {
  5. public void onArticleSelected(Uri articleUri);
  6. }
  7. ...
  8. }
  1. public static class FragmentA extends ListFragment {
  2. OnArticleSelectedListener mListener;
  3. ...
  4. @Override
  5. public void onAttach(Activity activity) {
  6. super.onAttach(activity);
  7. try {
  8. mListener = (OnArticleSelectedListener) activity;
  9. } catch (ClassCastException e) {
  10. throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
  11. }
  12. }
  13. ...
  14. }

以上是结合官网,归纳的。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注