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
which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle.
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
Locate the JAR file for the library you want to use and copy it into the
For example, the library that supports API level 4 and up is located at
Update your manifest file to set the minimum API level to
You can find all the API reference documentation for the Support Library in the platform docs at
Warning: To be sure that you don't accidentally use new APIs on an older system version, be certain that you import the
and related APIs from the
When creating an activity that hosts fragments while using the Support Library, you must also extend the
instead of the traditional
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
the
to define the layout.
For
instance, when the activity's
is called, any fragments in the activity also receive a call to
Here is an example layout file that adds two fragments to an activity when the device screen is considered "large" (specified
by the
in the directory name).
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.
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
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
create a
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
An
important rule when dealing with fragments—especially those that you add at runtime—is that the fragment must have a container
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
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
layout is used when the device screen is smaller than large because the screen does not fit both fragments at the same time.
Inside your activity, call
get a
the Support Library APIs. Then call
create a
call
add a fragment.When you're ready to make the changes, you must call
For example, here's how to add a fragment to the previous layout:
Because the fragment has been added to the
at runtime—instead of defining it in the activity's layout with a
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
you commit the
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:
The
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
UI components and activity behaviors into modules ,You can create these modules with the
Fragmentclass,
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
libsdirectory 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
4and 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
Fragmentclass
and related APIs from the
android.support.v4.apppackage:
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
FragmentActivityclass
instead of the traditional
Activityclass.
Creating a Fragment
You can think of a fragment as a modular section of an activity, which has itsown 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
Fragmentclass.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
largequalifier
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
FragmentManagerclass
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
FragmentManagerto
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
Viewin
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
largequalifier, 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
FragmentManagerusing
the Support Library APIs. Then call
beginTransaction()to
create a
FragmentTransactionand
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
FrameLayoutcontainer
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.BackStackEntryAPIs.
Communicating with Other Fragments
相关文章推荐
- Building a Dynamic UI with Fragments
- android开发官方教程之Building a Dynamic UI with Fragments
- Building a Dynamic UI with Fragments
- Android官方Training阅读笔记 ---- Building a Dynamic UI with Fragments(Creating a Fragment) (一)
- Building a Dynamic UI with Fragments
- Building a Dynamic UI with Fragments ---- Communicating with Other Fragme (三)
- AndroidTraining学习------Building-a-Dynamic-UI-with-Fragments-
- lesson 4 Building a Dynamic UI with Fragments
- (四)Building a Dynamic UI with Fragments使用fragment构建动态用户界面
- Building a Dynamic UI with Fragments
- Android官方Training阅读笔记 ---- Building a Dynamic UI with Fragments(Building a Flexible UI) (二)
- Training—Building a Dynamic UI with Fragments
- Building a Dynamic UI with Fragments
- Android training(1)-Building a Dynamic UI with Fragments(用碎片创造一个动态的UI)(A)
- Android training(1)-Building a Dynamic UI with Fragments(用碎片创造一个动态的UI)(B)
- Android training(1)-Building a Dynamic UI with Fragments(用碎片创造一个动态的UI)(C)
- Building a Dynamic UI with Fragments笔记
- android-Building a Dynamic UI with Fragments
- Building a Dynamic UI with Fragments - Building a Flexible UI
- Building a Dynamic UI with Fragments