Android培训翻译_与其它Fragment通信

This lesson teaches you to

  1. Define an Interface
    定义一个接口
  2. Implement the Interface
    实现该接口
  3. Deliver a Message to a Fragment
    将信息传递给Fragment

You should also read

Try it out

下载示例代码(FragmentBasics.zip)


 

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior. Once you have defined these reusable Fragments, you can associate them with an Activity and connect them with the application logic to realize the overall composite UI.
为了重用Fragment UI组件,你应该建立一个完全独立的、模块化的定义了自己布局和行为的组件。一旦你定义了这些可重用的Fragment,你可以用一个Activity去关联他们,并用程序逻辑连接它们以实现整体复合UI。

 

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
你经常想要一个fragment与另一个通信,例如基于用户事件来更新内容。所有的fragment到fragment的通信都是通过关联Activity来进行的。两个Fragment不应该直接通信。

 

Define an Interface 定义一个接口


To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
为了让Fragment与它的Activity通信,你应该在这个Fragment类中定义一个接口,并在Activity中实现它。Fragment在onAttach() 生命周期方法中捕获接口的实现,接着便可以调用接口方法来与Activity通信。

 

Here is an example of Fragment to Activity communication:
下面是一个Fragment与Activity通信的例子:

 

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    // 容器Activity必须实现这个接口

    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented 
        // 确认容器activity已经实现接口

        // the callback interface. If not, it throws an exception 
        // 回调接口。如果没有,抛出异常

        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
        }
    }
    ...
}

 

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallbackinstance of the OnHeadlineSelectedListener interface.
现在fragment可以通过使用OnHeadlineSelectedListener接口的mCallback实例,调用 onArticleSelected() 方法(或接口中的其它方法),来向activity传递信息了。

 

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
例如,当用户点击一个列表中的项时,fragment里下面的方法就会被调用。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    // 传送事件给宿主activity

    mCallback.onArticleSelected(position);
}

 

Implement the Interface 实现接口


In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.
为了从fragment接收事件回调,寄宿它的activity必须实现这个fragment类定义的接口。

 

For example, the following activity implements the interface from the above example.
例如,下面的activity实现了上面例子中的接口。

public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...
    
    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment 
        // 用户从HeadlinesFragment选择了一篇文章的标题 
        // Do something here to display that article 显示文章

    }
}

 

 

Deliver a Message to a Fragment 向Fragment传递信息


The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.
宿主activity可以用findFragmentById()捕获Fragment实例,以向fragment传递信息。

 

For instance, imagine that the activity shown above may contain another fragment that's used to display the item specified by the data returned in the above callback method. In this case, the activity can pass the information received in the callback method to the other fragment that will display the item:
例如,想象一下,上面的activity可能包含另一个fragment,它用来显示上面回调方法返回的数据所指定的(文章)项。在这个例子中,activity可以传递回调方法接收的信息给其它的fragment,这个fragment将会显示项(的详细信息)。

public static class MainActivity extends Activity 
implements HeadlinesFragment.OnHeadlineSelectedListener{ ... public void onArticleSelected(int position) { // The user selected the headline of an article from the HeadlinesFragment
// 用户从HeadlinesFragment中选则了一个文章的标题
// Do something here to display that article
// 显示文章 ArticleFragment articleFrag = (ArticleFragment)getSupportFragmentManager()
.findFragmentById(R.id.article_fragment);
if (articleFrag != null) { // If article frag is available, we're in two-pane layout...
// 如果文章的fragment可用,我们在双窗格布局中...
// Call a method in the ArticleFragment to update its content
// 调用ArticleFragment中的一个方法更新它的内容
articleFrag.updateArticleView(position); } else { // Otherwise, we're in the one-pane layout and must swap frags...
// 否则我们在单窗格布局中,必须置换fragment...
// Create fragment and give it an argument for the selected article
// 创建一个fragment并将选中的文章作为一个参数传给它 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
// 用这个fragment替换掉fragment_container容器视图中的内容,并将事务添加到后退栈中以便用户可以导航回退

            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction 提交事务

            transaction.commit();
        }
    }
}

posted on 2012-08-21 15:04  梵谷星辰  阅读(2203)  评论(1编辑  收藏  举报

导航