2012年11月2日金曜日

Fragment Adding a user interface

 

A fragment is usually used as part of an activity's user interface and contributes its own layout to the activity.

To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.

Note: If your fragment is a subclass of ListFragment, the default implementation returns a ListView fromonCreateView(), so you don't need to implement it.

To return a layout from onCreateView(), you can inflate it from a layout resource defined in XML. To help you do so, onCreateView() provides a LayoutInflater object.

For example, here's a subclass of Fragment that loads a layout from the example_fragment.xml file:

public static class ExampleFragment extends Fragment {      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,                               Bundle savedInstanceState) {          // Inflate the layout for this fragment          return inflater.inflate(R.layout.example_fragment, container, false);      }  }

The container parameter passed to onCreateView() is the parent ViewGroup (from the activity's layout) in which your fragment layout will be inserted. The savedInstanceStateparameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed (restoring state is discussed more in the section about Handling the Fragment Lifecycle).

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.
  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it's going.
  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)

Now you've seen how to create a fragment that provides a layout. Next, you need to add the fragment to your activity.

Adding a fragment to an activity

Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout:

  • Declare the fragment inside the activity's layout file.

    In this case, you can specify layout properties for the fragment as if it were a view. For example, here's the layout file for an activity with two fragments:

    <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="horizontal"      android:layout_width="match_parent"      android:layout_height="match_parent">      <fragment android:name="com.example.news.ArticleListFragment"              android:id="@+id/list"              android:layout_weight="1"              android:layout_width="0dp"              android:layout_height="match_parent" />      <fragment android:name="com.example.news.ArticleReaderFragment"              android:id="@+id/viewer"              android:layout_weight="2"              android:layout_width="0dp"              android:layout_height="match_parent" />  </LinearLayout>

    The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the layout.

    When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout. The system inserts the Viewreturned by the fragment directly in place of the <fragment> element.

    Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:

    • Supply the android:id attribute with a unique ID.
    • Supply the android:tag attribute with a unique string.
    • If you provide neither of the previous two, the system uses the ID of the container view.
  • Or, programmatically add the fragment to an existing ViewGroup.

    At any time while your activity is running, you can add fragments to your activity layout. You simply need to specify a ViewGroup in which to place the fragment.

    To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction. You can get an instance of FragmentTransaction from your Activitylike this:

    FragmentManager fragmentManager = getFragmentManager()  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example:

    ExampleFragment fragment = new ExampleFragment();  fragmentTransaction.add(R.id.fragment_container, fragment);  fragmentTransaction.commit();

    The first argument passed to add() is the ViewGroup in which the fragment should be placed, specified by resource ID, and the second parameter is the fragment to add.

    Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.

Adding a fragment without a UI

The examples above show how to add a fragment to your activity in order to provide a UI. However, you can also use a fragment to provide a background behavior for the activity without presenting additional UI.

To add a fragment without a UI, add the fragment from the activity using add(Fragment, String) (supplying a unique string "tag" for the fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a view in the activity layout, it does not receive a call to onCreateView(). So you don't need to implement that method.

Supplying a string tag for the fragment isn't strictly for non-UI fragments—you can also supply string tags to fragments that do have a UI—but if the fragment does not have a UI, then the string tag is the only way to identify it. If you want to get the fragment from the activity later, you need to use findFragmentByTag().

For an example activity that uses a fragment as a background worker, without a UI, see theFragmentRetainInstance.java sample.

0 件のコメント:

コメントを投稿