Android类参考---Fragment(一)

1. 继承关系

java.lang.Object

|__android.app.Fragment

实现接口:ComponentCallbacks2 View.OnCreateContextMenuListener

引入版本:API Level 11

已知的子类:

DialogFragment、ListFragment、PreferenceFragment、WebViewFragment

2. 类概要

一个Fragment是应用程序的用户界面或行为的一个片段,它能够被放置在一个Activity中。通过FragmentManager对象来实现与Fragment对象的交互,能够通过Activity.getFragmentManager()方法和Fragment.getFragmentManager()方法来获取FragmentManager对象。

Fragment类有着广泛的应用,它的核心是代表了一个正在较大的Activity中运行的特俗的操作或界面。Fragment对象跟它所依附的Activity对象是紧密相关的,并且不能被分开使用。尽管Fragment对象定义了它们自己的生命周期,但是这个生命周期要依赖与它所在的Activity:如果该Activity被终止,那么它内部的Fragment是不能被启动的;当Activity被销毁时,它内部的所有Fragment对象都会被销毁。

所有的Fragment子类都必须包含一个公共的空的构造器。在需要的时候,Framework会经常重新实例化Fragment类,在特殊的状态恢复期间,需要能够找到这个构造器来实例化Fragment类。如果空的构造器无效,那么在状态恢复期间会导致运行时异常发生。

较旧的平台

尽管Fragment API是在HONEYCOMB版本中被引入的,但是通过FragmentActivity也能够在较旧的平台上使用该API。

声明周期

尽管Fragment对象的生命周期要依附于它所在的Activity对象,但是它也有自己标准的活动周期,它包含了基本的活动周期方法,如onResume(),但是同时也包含了与Activity和UI交互相关的重要方法。

显示Fragment时(跟用户交互)要调用的核心的生命周期方法如下:

1. 把Fragment对象跟Activity关联时,调用onAttach(Activity)方法;

2. Fragment对象的初始创建时,调用onCreate(Bundle)方法;

3. onCreateView(LayoutInflater, ViewGroup, Bundle)方法用于创建和返回跟Fragment关联的View对象;

4. onActivityCreate(Bundle)方法会告诉Fragment对象,它所依附的Activity对象已经完成了Activity.onCreate()方法的执行;

5. onStart()方法会让Fragment对象显示给用户(在包含该Fragment对象的Activity被启动后);

6. onResume()会让Fragment对象跟用户交互(在包含该Fragment对象的Activity被启恢复后)。

Fragment对象不再使用时,要反向回调的方法:

1. 因为Fragment对象所依附的Activity对象被挂起,或者在Activity中正在执行一个修改Fragment对象的操作,而导致Fragment对象不再跟用户交互时,系统会调用Fragment对象的onPause()方法;

2. 因为Fragment对象所依附的Activity对象被终止,或者再Activity中正在执行一个修改Fragment对象的操作,而导致Fragment对象不再显示给用户时,系统会调用Fragment对象的onStop()方法。

3. onDestroyView()方法用于清除跟Fragment中的View对象关联的资源;

4. Fragment对象的状态被最终清理完成之后,要调用onDestroy()方法;

5. 在Fragment对象不再跟它依附的Activity关联的时候,onDetach()方法会立即被调用。

 

布局

Fragment对象能够被用于应用程序的布局,它会让代码的模块化更好,并且针对Fragment所运行的屏幕,让用户界面的调整更加容易。例如,一个简单的由项目列表和项目明细表示所组成的程序。

一个Activity的布局XML能够包含要嵌入到布局内部的Fragment实例的<fragment>标签。例如,下例中在布局中嵌入了一个Fragment对象:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent" android:layout_height="match_parent">
   
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
           
android:id="@+id/titles"
           
android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>

以下是布局被安装到Activity中的通常方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
   
super.onCreate(savedInstanceState);

    setContentView
(R.layout.fragment_layout);
}

依赖ListFragment对象,要显示列表的标题是相当简单的。要注意的是,点击一个列表项的实现,会依赖当前Activity的布局,它既可以创建一个新的Fragment用于显示该项目的明细,也可以启动一个新的Activity用于显示项目的明细。

public static class TitlesFragment extends ListFragment {
   
boolean mDualPane;
   
int mCurCheckPosition = 0;

   
@Override
   
public void onActivityCreated(Bundle savedInstanceState) {
       
super.onActivityCreated(savedInstanceState);

       
// Populate list with our static array of titles.
        setListAdapter
(new ArrayAdapter<String>(getActivity(),
                android
.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

       
// Check to see if we have a frame in which to embed the details
       
// fragment directly in the containing UI.
       
View detailsFrame = getActivity().findViewById(R.id.details);
        mDualPane
= detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

       
if (savedInstanceState != null) {
           
// Restore last state for checked position.
            mCurCheckPosition
= savedInstanceState.getInt("curChoice", 0);
       
}

       
if (mDualPane) {
           
// In dual-pane mode, the list view highlights the selected item.
            getListView
().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
           
// Make sure our UI is in the correct state.
            showDetails
(mCurCheckPosition);
       
}
   
}

   
@Override
   
public void onSaveInstanceState(Bundle outState) {
       
super.onSaveInstanceState(outState);
        outState
.putInt("curChoice", mCurCheckPosition);
   
}

   
@Override
   
public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails
(position);
   
}

   
/**
     * Helper function to show the details of a selected item, either by

     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */

   
void showDetails(int index) {
        mCurCheckPosition
= index;

       
if (mDualPane) {
           
// We can display everything in-place with fragments, so update
           
// the list to highlight the selected item and show the data.
            getListView
().setItemChecked(index, true);

           
// Check what fragment is currently shown, replace if needed.
           
DetailsFragment details = (DetailsFragment)
                    getFragmentManager
().findFragmentById(R.id.details);
           
if (details == null || details.getShownIndex() != index) {
               
// Make new fragment to show this selection.
                details
= DetailsFragment.newInstance(index);

               
// Execute a transaction, replacing any existing fragment
               
// with this one inside the frame.
               
FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft
.replace(R.id.details, details);
                ft
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft
.commit();
           
}

       
} else {
           
// Otherwise we need to launch a new activity to display
           
// the dialog fragment with selected text.
           
Intent intent = new Intent();
            intent
.setClass(getActivity(), DetailsActivity.class);
            intent
.putExtra("index", index);
            startActivity
(intent);
       
}
   
}
}

明细Fragment对象只会显示所选项目的详细文本字符串,它是基于内置在应用中的一个字符数组的索引来获取的:

public static class DetailsFragment extends Fragment {
   
/**
     * Create a new instance of DetailsFragment, initialized to

     * show the text at 'index'.
     */

   
public static DetailsFragment newInstance(int index) {
       
DetailsFragment f = new DetailsFragment();

       
// Supply index input as an argument.
       
Bundle args = new Bundle();
        args
.putInt("index", index);
        f
.setArguments(args);

       
return f;
   
}

   
public int getShownIndex() {
       
return getArguments().getInt("index", 0);
   
}

   
@Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container,
           
Bundle savedInstanceState) {
       
if (container == null) {
           
// We have different layouts, and in one of them this
           
// fragment's containing frame doesn't exist.  The fragment
           
// may still be created from its saved state, but there is
           
// no reason to try to create its view hierarchy because it
           
// won't be displayed.  Note this is not needed -- we could
           
// just run the code below, where we would create and return
           
// the view hierarchy; it would just never be used.
           
return null;
       
}

       
ScrollView scroller = new ScrollView(getActivity());
       
TextView text = new TextView(getActivity());
       
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
               
4, getActivity().getResources().getDisplayMetrics());
        text
.setPadding(padding, padding, padding, padding);
        scroller
.addView(text);
        text
.setText(Shakespeare.DIALOGUE[getShownIndex()]);
       
return scroller;
   
}
}

在用户点击标题的情况下,在当前的Activity中没有明细容器,因此标题Fragment的点击事件代码会启动一个新的显示明细Fragment的Activity:

public static class DetailsActivity extends Activity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);

       
if (getResources().getConfiguration().orientation
               
== Configuration.ORIENTATION_LANDSCAPE) {
           
// If the screen is now in landscape mode, we can show the
           
// dialog in-line with the list so we don't need this activity.
            finish
();
           
return;
       
}

       
if (savedInstanceState == null) {
           
// During initial setup, plug in the details fragment.
           
DetailsFragment details = new DetailsFragment();
            details
.setArguments(getIntent().getExtras());
            getFragmentManager
().beginTransaction().add(android.R.id.content, details).commit();
       
}
   
}
}

但是,屏幕可能足够显示标题列表和当前所选标题相关的明细。对于在横向屏幕上这样的布局,可以被放置在layout-land下面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="horizontal"
   
android:layout_width="match_parent" android:layout_height="match_parent">

   
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
           
android:id="@+id/titles" android:layout_weight="1"
           
android:layout_width="0px" android:layout_height="match_parent" />

   
<FrameLayout android:id="@+id/details" android:layout_weight="1"
           
android:layout_width="0px" android:layout_height="match_parent"
           
android:background="?android:attr/detailsElementBackground" />

</LinearLayout>

要注意的是,以上代码是如何调整这种可选的UI流的:标题Fragment对象被嵌入到该Activity内部的明细Fragment对象中,并且如果Fragment对象运行在一个有显示明细空间的配置环境中,那么明细Activity会由它自己来完成。

当由于配置的改变而导致Activity所持有的这些Fragment对象重启的时候,它们新的Fragment实例可以使用与之前所使用的布局不同的布局。在这种情况中,之前所有的Fragment对象依然会被实例化,并运行在新的实例中。但是任何不在跟<fragment>关联的View对象将不会再被创建,并且重isInLayout()方法中返回false

在把FragmentView对象绑定到父容器的时候,<fragment>标签的属性被用于控制提供给LayoutParams对象的信息,它们能够作为Fragment对象中的onInflate(Activity, AttributeSet, Bundle)方法的参数来解析。

正在实例化的Fragment对象必须要有某些类型唯一标识,以便在它的父Activity在销毁并重建的时候,能够被重新关联到之前的实例。可以使用以下方法来实现这种关联:

1. 如果没有明确的指定,则使用容器的View ID来标识;

2. 使用<fragment>元素的android:tag属性,给Fragment对象元素提供一个特定的标签名称;

3. 使用<fragment>元素的android:id属性,给Fragment对象的元素提供一个特定的标识。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值