Building a dynamic UI with fragments

To create a dynamic and multi-pane user interface on Android, you need to encapsulate UI components and activity behaviors into modules ,You can create these modules with the Fragment class, which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle.

Using the Support Library

set up your app to use the Support Library in order to use fragments to build a dynamic app UI.



To set up your project:

  1. Download the Android Support package using the SDK Manager.
  2. Create a libsdirectory at the top level of your Android project.
  3. Locate the JAR file for the library you want to use and copy it into the libs/directory.

    For example, the library that supports API level 4 and up is located at<sdk>/extras/android/support/v4/android-support-v4.jar.

  4. Update your manifest file to set the minimum API level to 4 and the target API level to the latest release:
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />

You can find all the API reference documentation for the Support Library in the platform docs atandroid.support.v4.*.

Warning: To be sure that you don't accidentally use new APIs on an older system version, be certain that you import the Fragment class and related APIs from the android.support.v4.app package:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...

When creating an activity that hosts fragments while using the Support Library, you must also extend theFragmentActivity class instead of the traditional Activity class.

Creating a Fragment

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
extend the Fragment class.use the onCreateView() callback to define the layout.
 For instance, when the activity's onPause() method is called, any fragments in the activity also receive a call toonPause().
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

Here is an example layout file that adds two fragments to an activity when the device screen is considered "large" (specified by the  large  qualifier in the directory name).

res/layout-large/news_articles.xml:

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

    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

    <fragment android:name="com.example.android.fragments.ArticleFragment"
              android:id="@+id/article_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />

</LinearLayout>
When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot  remove the fragment at runtime. If you plan to swap your fragments in and out during user interaction, you must add the fragment to the activity when the activity first starts, as shown in the next lesson.

Building a Flexible UI


 Two fragments, displayed in different configurations for the same activity on different screen sizes. On a large screen, both fragment fit side by side, but on a handset device, only one fragment fits at a time so the fragments must replace each other as the user navigates.

The FragmentManager class provides methods that allow you to add, remove, and replace fragments to an activity at runtime in order to create a dynamic experience.

Rather than defining the fragments for an activity in the layout file,ou can add a fragment to the activity during the activity runtime. This is necessary if you plan to change fragments during the life of the activity.

To perform a transaction such as add or remove a fragment, you must use the FragmentManager to create aFragmentTransaction, which provides APIs to add, remove, replace, and perform other fragment transactions.

you should add the initial fragment(s) to the activity during the activity's onCreate() method.

An important rule when dealing with fragments—especially those that you add at runtime—is that the fragment must have a container View in the layout in which the fragment's layout will reside.

In order to replace one fragment with another, the activity's layout includes an empty FrameLayoutthat acts as the fragment container.

Notice that the filename is the same as the layout file in the previous lesson, but the layout directory does nothave the large qualifier, so this layout is used when the device screen is smaller than large because the screen does not fit both fragments at the same time.

res/layout/news_articles.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Inside your activity, call  getSupportFragmentManager()  to get a  FragmentManager  using the Support Library APIs. Then call  beginTransaction()  to create a  FragmentTransaction  and call  add()  to add a fragment.When you're ready to make the changes, you must call commit().

For example, here's how to add a fragment to the previous layout:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create an instance of ExampleFragment
            HeadlinesFragment firstFragment = new HeadlinesFragment();
            
            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());
            
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}
Because the fragment has been added to the  FrameLayout  container at runtime—instead of defining it in the activity's layout with a  <fragment>  element—the activity can remove the fragment and replace it with a different one.

Keep in mind that when you perform fragment transactions, such as replace or remove one, it's often appropriate to allow the user to navigate backward and "undo" the change. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit theFragmentTransaction.

When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced.

Example of replacing one fragment with another:

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

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

// Commit the transaction
transaction.commit();

The addToBackStack() method takes an optional string parameter that specifies a unique name for the transaction. The name isn't needed unless you plan to perform advanced fragment operations using theFragmentManager.BackStackEntry APIs.

Communicating with Other Fragments


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值