Fragments | Android Developer

Definition

  • A Fragment represents a behavior or a potion of user interface in an Activity.
  • You can combile multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
  • A Fragment has its own life cycle, receives its own input events, and you can add or remove it while the activity is running. (sub activity)
  • A Fragment‘s lifecycle is directly affected by its host activity‘s lifecycle. It follows the activity‘s lifecycle, except for in resuming state. The fragment‘s transaction can be pushed into the backstack.

Two ways to add a fragment to acitvity

  • Define <fragment>...</fragment> in layout file.
  • In code, add a fragment to an existing ViewGroup.

Design philosophy

  • 在3.0(API 11)出现,目的是满足动态、灵活的UI设计,避免view hierarchy的频繁变化。
  • 对于目的是复用的Fragment A,尽量避免在另一个Fragment B里操作它的生命周期(因为在另一个场景下很可能就没有B了)

Creating a fragment

在实现一个Fragment时,通常需要override以下方法

  • onCreate(),完成初始化功能
  • onCreateView(),Fragment首次绘制UI时会调用该方法,返回根View,如果Fragment不需要UI,则返回null
  • onPause(),commit changes

几种Fragment

  • DialogFragment
  • ListFragment
  • PreferenceFragment

创建Fragment的几种方法

  • 布局文件里声明
<fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
       android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
  • Programmatically (in Activity)
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment f = new SampleFragment();
ft.add(R.id.fragment_container, f);
fm.commit();

无UI的Fragment

  • 使用 add(Fragment fragment, String tag) 进行添加
  • 无需重写 onCreateView 方法
  • 使用 findFragmentByTag 获取该Fragment

Managing Fragments

FragmentManager 的作用

  • 获取Fragment:findFragmentById(有UI),findFragmentByTag(无UI)
  • 使Fragment出栈,popBackStack(),模拟用户点击Back按钮。(用处何在?)
  • 在BackStack中增加Listener,addOnBackStackChangeListener()

Performing Fragment Transactions

使用BackStack来存储Fragment的状态

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

在commit()前使用setTransaction()来增加动画效果

Communicating with the Activity

彼此获取引用

  • Fragment通过getActivity()来获取宿主Activity的引用
  • Activity通过getFragmentManager().findFragmentById()来获取嵌入的Fragment引用

在Fragment中实现对Activity的Callback:声明一个接口,在onAttach()时将实现该接口的Activity引用保存,在需要通知Activity时调用接口中的方法

public static class FragmentA extends ListFragment {  private OnArticleSelectedListener mListener;
    ...
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    ...
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Append the clicked item‘s row ID with the content provider Uri
        Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
        // Send the event and Uri to the host activity
        mListener.onArticleSelected(noteUri);
    }
    ...
}

Fragment可以注册Options Menu与Context Menu,从而接收到onOptionsItemSelected()等事件

Handling the Fragment Lifecycle

Fragment的生命周期与Activity类似

  • create阶段,onAttach() -> onCreate() -> onCreateView() -> onActivityCreated()
  • 最大的不同在于Activity自动入栈,而Fragment需要显式声明

在宿主Activity的Resume阶段,可以自由进行Fragment的增添/删除

时间: 2024-10-12 05:00:00

Fragments | Android Developer的相关文章

[share]How to Become a Lazy but Productive Android Developer

How to Become a Lazy but Productive Android Developer How can we optimize throughput time for writing the business logic for the app and avoid lazy code to write? by Paresh Mayani · Dec. 16, 13 · Mobile Zone Like (1) Comment (3) Save Tweet 21.63k Vie

This Android SDK requires Android Developer Toolkit version 23.0.0 or above

This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 12.0.0.v201106281929-138431. Please update ADT to the latest version 22.0.0 一般这种原因是误更新了SDK,导致SDK版本过高,ECLIPSE提示需要更新ADT. 解决办法如下: 找到android-sdk-windows\tools

解决在sdk manager中更新文件后出现This Android SDK requires Android Developer Toolkit version 23.1的错误

起因:在sdksdk manager中更新了adt及其他的支持库后,eclipse报错:This Android SDK requires Android Developer Toolkit version 23.1的错误.可是sdksdk manager中明明显示23.1的adt是已经installed的了呀,这就奇怪了.. 解决办法:Help -> Install New Software -> Add ->http://dl-ssl.google.com/android/eclip

[转] This Android SDK requires Android Developer Toolkit version 23.0.0 or above

问题描述: 上一篇讲到解决Appcompat_V7问题要降低adt版本,于是就换旧版本22.3.0啊,重新打开Eclipse,立马弹出: This Android SDK requires Android Developer Toolkit version 23.0.0 or above.  Current version is 12.0.0.v201106281929-138431. 一般这种原因是误更新了SDK,导致SDK版本过高,ECLIPSE提示需要更新ADT. 于是我觉得是我的sdk版

this android sdk requires android developer toolkit version

this android sdk requires android developer toolkit version 10.0.0 or above. current version is 8.0.1.v201012062107-82219. please update adt to the latest version 解决HELP-INSTALL NEW SOFTWARE-ADT - https://dl-ssl.google.com/android/eclipse/ this andro

【边做项目边学Android】小白会遇到的问题--This Android SDK requires Android Developer Toolkit version 23.0.0 or above

问题描写叙述: 上一篇讲到解决Appcompat_V7问题要减少adt版本号,于是就换旧版本号22.3.0啊,又一次打开Eclipse.立刻弹出: This Android SDK requires Android Developer Toolkit version 23.0.0 or above.  Current version is 12.0.0.v201106281929-138431. 一般这样的原因是误更新了SDK,导致SDK版本号过高,ECLIPSE提示须要更新ADT. 于是我认为

微软职位内部推荐-Senior Android Developer

微软近期Open的职位: Position: Senior SDE-- Mobile Products Android/iOS/WP Senior Developer Contact Person: Winnie Wei ([email protected]) Location: Beijing Roles & Responsibilities: As a Software Design Engineer, you will work with PM, UX and Test teams to

This android SDk requires Android developer......

在用SDK manager更新SDK后,启动Eclipse提示This Android SDK requires Android Developer Toolkit version 23.0.0 or above. 需要更新ADT. 进入文件......\sdk\tools\lib,找到plugin.prop 打开后,显示 # begin plugin.prop  plugin.version=23.0.0 # end plugin.prop 此时,只需将23.0.0改为22.0.0或者更低的版

Android初学者Eclispe环境启动遇This Android SDK requires Android Developer Toolkit version 23.0.0 or above

当我们进行Android开发,配置安装环境Eclispe&SDK&ADT过程中,在SDK在线安装后,重新登录Eclispe,会出现警告框:This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.2.1.v.201309180102-833290. Please update ADT to the latest version. 问题在与:在线安装SD