Android官方入门文档[17]构建灵活的UI
Building a Flexible UI
构建灵活的UI
This lesson teaches you to
1.Add a Fragment to an Activity at Runtime
2.Replace One Fragment with Another
You should also read
?Fragments
?Supporting Tablets and Handsets
这节课教你
1.在运行时新增一个片段给一个活动
2.用另一片段替换一个片段
你也应该阅读
?片段
?支持平板电脑和手持设备
Try it out
试试吧
Download the sample
FragmentBasics.zip
下载样本
FragmentBasics.zip
When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space.
当设计你的应用程序支持多种屏幕尺寸,您可以重用片段在不同的布局结构优化的基础上可用的屏幕空间的用户体验。
For example, on a handset device it might be appropriate to display just one fragment at a time for a single-pane user interface. Conversely, you may want to set fragments side-by-side on a tablet which has a wider screen size to display more information to the user.
例如,一个手持设备上也可能是适当的时间为一个单窗格的用户界面,来显示只有一个片段。反之,你可能要设置片段并排侧片有更宽的屏幕尺寸可显示更多的信息给用户。
Figure 1. Two fragments, displayed in different configurations for the same activity on different screen sizes. On a large screen, both fragments 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.
图1的两个片段,用于在不同的屏幕尺寸相同的活性显示在不同的配置。在大屏幕上,这两个片段拟合并排,但一个手持设备上,只有一个片段装配在一个时间,以便用户导航片段必须相互取代。
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.
该FragmentManager类提供了一些方法,使您可以添加,删除和替换片段活动在运行时,以创造一个动态的体验。
Add a Fragment to an Activity at Runtime
在运行时新增一个片段给一个活动
--------------------------------------------------------------------------------
Rather than defining the fragments for an activity in the layout file—as shown in the previous lesson with the <fragment> element—you 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.
为了进行交易,如添加或删除片段,则必须使用FragmentManager创建FragmentTransaction,它提供的API来添加,删除,替换,以及执行其他片段交易。
If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity's onCreate() method.
如果你的活动可以使片段被删除,取而代之,你应该活动的OnCreate()方法中添加初始片段活动。
An important rule when dealing with fragments—especially when adding fragments at runtime—is that your activity layout must include a container View in which you can insert the fragment.
一个重要的规则时的片段,尤其是在加时的片段与处理运行时,是你的活动布局必须有一个容器视图,可以在其中插入片段。
The following layout is an alternative to the layout shown in the previous lesson that shows only one fragment at a time. In order to replace one fragment with another, the activity's layout includes an empty FrameLayout that acts as the fragment container.
下面的布局是一种替代上一课中所示的布局只显示一次一个片段。为了取代一个片段与另一种,活动的布局包括一个空的FrameLayout充当片段容器。
Notice that the filename is the same as the layout file in the previous lesson, but the layout directory does not have 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.
请注意,文件名是一样的,在上一课布局文件,但布局目录没有大的限定符,所以这种布局时使用的设备的屏幕比large小,因为屏幕在同一时间不适合两个片段。
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.
在你的活动,调用getSupportFragmentManager()来获得使用支持库API的FragmentManager。然后调用的BeginTransaction()来创建一个FragmentTransaction并调用增加()来添加一个片段。
You can perform multiple fragment transaction for the activity using the same FragmentTransaction. When you're ready to make the changes, you must call commit().
可以使用相同的FragmentTransaction活性执行多个片段事务。当你准备好了做出改变,你必须调用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 a new Fragment to be placed in the activity layout 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.
因为该片段已被添加了<fragment>元素的活性定义它在活动的布局可以删除片段,并将其与不同的一个replace到的FrameLayout容器在运行时,代替。
Replace One Fragment with Another
用另一片段替换一个片段
--------------------------------------------------------------------------------
The procedure to replace a fragment is similar to adding one, but requires the replace() method instead of add().
步骤替换的片段是类似于添加一种,但需要replace()方法,而不是add()。
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.
请记住,当你执行片段交易,如替换或删除一个,它往往是适当的,允许用户浏览后退,“撤销”的转变。为了使用户能够通过碎片交易向后导航,你必须调用addToBackStack(),您提交FragmentTransaction之前。
Note: 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 showArticleFragment 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 backtransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.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.
该addToBackStack()方法接受一个可选的字符串参数,指定一个唯一的名称进行交易。除非你打算执行使用FragmentManager.BackStackEntry API的先进片段操作的名称是不需要的。
Next: Communicating with Other Fragments
下一页:通信与其它片段
本文翻译自:https://developer.android.com/training/basics/fragments/fragment-ui.html