Android培训翻译_构建灵活的UI

 

This lesson teaches you to
这一课教你

  • Add a Fragment to an Activity at Runtime
    在运行时添加Fragment
  • Replace One Fragment with Another
    更换Fragment
  • You should also read

  • Fragments
  • Supporting Tablets and Handsets
    支持平板和手持设备
  • Try it out

    下载示例代码(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.
    设计你的应用程序支持宽屏尺寸时,你可以在不同的布局配置中重复使用fragment,以基于可用的屏幕空间来优化用户体验。

     

    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.
    例如,在手持设备上,弹窗口用户界面上一次可能只适合显示一个fragment。反之,在平板这样的宽屏尺寸上你可能想要并排的几个fragment来向用户显示更多的信息。

     

    Figure 1. 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.
    图1.同一个Activity不同配置两个fragment,显示在不同尺寸的屏幕上。在大屏幕上,两个fragment并排放置,但是在手持设备上,一次只有一个fragment显示,因此两个fragment必须彼此交替,为用户导航。

     

    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. FragmentManager类提供了一系列方法,允许你在运行时向一个activity添加,移除或替换fragments,来创建动态体验。

     

    Add a Fragment to an Activity at Runtime
    在运行时向Activity添加Fragment


    Rather than defining the fragments for an activity in the layout file—as shown in theprevious 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.
    比起上节课演示的,在一个布局文件里为activity定义fragment,你最好能在activity运行时向activity添加fragment。如果你打算在activity活动时改变fragment,这但是必要的。

     

    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.
    执行事务,例如添加或移除fragment,你必须使用FragmentManager来创建一个FragmentTransaction。这个对象提供了添加、移除和执行其它fragment事务的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'sonCreate() method.
    如果你的activity允许移除和替换fragment,你应该在activity onCreate()中为activity添加初始的fragment。

     

    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.
    处理fragment,尤其是在运行时添加它们时的一个重要规则:布局中必须要有一个放置fragment 的View 容器。

     

    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.
    下面的布局是上节课所展示的一次只显示一个fragment布局的替代方案。为了用一个fragment去替换另一个,activity布局包含了一个空的FrameLayout作为fragment的容器。

     

    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"限定词,因此这个布局被用在小于large的设备屏幕上,因为这个屏幕不能同时适应两个fragment。

    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.
    在activity内部,调用 getSupportFragmentManager() 获得一个 FragmentManager来使用支持库API。然后调用 beginTransaction()创建一个FragmentTransaction 调用add() 来添加一个fragment。

     

    You can perform multiple fragment transaction for the activity using the same FragmentTransaction. When you're ready to make the changes, you must callcommit().
    你可以用一个FragmentTransaction 为activity 运行多个fragment 事务。你准备改变时,必须调用commit()。

     

    For example, here's how to add a fragment to the previous layout:
    例如,这里展示如何向之前那个布局添加fragment。

     

    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.
    由于fragment是在运行时被添加到FrameLayout容器中,而不是用<fragment>元素在activity布局中定义的,因此activity可以移除fragment或者用个不同的来替换。

     

    Replace One Fragment with Another
    用一个Fragment替换另一个


    The procedure to replace a fragment is similar to adding one, but requires the replace() method instead of add().
    替换fragment的过程与添加类似,只是调用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 theFragmentTransaction.
    记住,当你运行像代替或移除这样的fragment事务时,常常适当允许用户导航后退或撤销之前的改变。为了允许用户在fragment 事务期间后退,你必须在提交FragmentTransaction前调用 addToBackStack()。

     

    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 notadd the transaction to the back stack, then the fragment is destroyed when removed or replaced.

    注: 当你移除或替换fragment并向后退栈中添加事务时,被移除的fragment会停止(不是销毁)。如果用户后退恢复了fragment,它将会重启。如果你不向后退栈中添加事务,当fragment移除或是被替换时就会被摧毁。

     

    Example of replacing one fragment with another:
    用一个fragment替换另一个的示例:

    // 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.

    addToBackStack()方法有个可选的字符串参数用来指定事务的唯一名称。这个名称不是必须的,除非你打算用FragmentManager.BackStackEntry API 进行一些高级的fragment操作。

posted on 2012-08-21 14:46  梵谷星辰  阅读(766)  评论(0编辑  收藏  举报

导航