您的位置:首页 > 产品设计 > UI/UE

Building a dynamic UI with fragments

2013-02-28 14:57 435 查看
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:

Download the Android Support package using the SDK Manager.
Create a
libs
directory at the top level of your Android project.
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
.

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 at
android.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 the
FragmentActivity
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 to
onPause()
.

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, youcannot 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 a
FragmentTransaction
,
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
FrameLayout
that
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 the
FragmentTransaction
.

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 the
FragmentManager.BackStackEntry
APIs.


Communicating with Other Fragments

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: