`
yidongkaifa
  • 浏览: 4051957 次
文章分类
社区版块
存档分类
最新评论

Building a Dynamic UI with Fragments---Building a Flexible UI

 
阅读更多

原文地址:https://developer.android.com/training/basics/fragments/fragment-ui.html

-------------------------------------------------------------------------------------------------------------------

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 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在不同屏幕大小上使用不同的配置显示两个框架。在大屏幕上,两个框架紧挨着放置,但是在手机设备上,同一时间只有一个框架,因此在用户点击导航时框架必须互相替换。

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类提供了一些方法,它们允许你动态地向一个activity添加、移除和替换框架,已达到一个动态的用户体验。

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.

不是在布局文件里定义一个activity的框架——正如上一节课里演示的一样,使用<fragment>元素——你可以在activity运行时刻向其添加框架。如果你打算在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,它提供了添加、移除、替换的APIs。

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.

如果你的activity允许移除和替换框架,你应该在onCreate()方法中向activity中添加初始的框架。

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.

处理框架时一个重要的规则——特别是你动态添加的那些——就是框架必须在布局中包含一个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.

下一个布局是在上一节课里演示过的一个可供选择的布局,在某一时刻它仅允许显示一个框架。为了替换框架,activity的布局包含了一个空的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标识符,因此当设备平布小于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.

在你的activity内部,使用Support Library APIs调用getSupportFragmentManager()来获得一个FragmentManager。然后调用beginTransaction()来创建一个 FragmentTransaction,再调用add()来添加一个框架。

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

因为框架已经动态地添加到FrameLayout中——而不是使用一个<fragment>元素在activity的布局中定义——activity可以移除和使用另一个来替换它。

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.

记住,当你执行一个框架事务时,例如替换或移除,允许用户通过导航返回和“撤销“变化经常是合适的。允许用户通过框架事务导航返回,你必须在确认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 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.

addToBackStack()方法接受一个可选择的字符串参数,指定了一个唯一的事务名称。除非你打算使用FragmentManager.BackStackEntry APIs执行高级的框架操作,这个名字是不需要的。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics