Android官方入门文档[18]与其他碎片通信

Android官方入门文档[18]与其他碎片通信

Communicating with Other Fragments
与其他碎片通信

This lesson teaches you to
1.Define an Interface
2.Implement the Interface
3.Deliver a Message to a Fragment

You should also read
?Fragments

这节课教你
1.定义一个接口
2.实现接口
3.传递一个消息给一个代码片段

你也应该阅读
?片段

Try it out
试试吧

Download the sample
FragmentBasics.zip
下载样本
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.
为了重用代码片段UI组件,你应该建立各自的定义自己的布局和行为完全独立的,模块化的组件。一旦你定义了这些可重复使用的片段,您可以用他们的活动联系起来,并与应用逻辑连接起来,实现整体复合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.
通常你想要一个代码片段与另一个通信,例如,以改变基于用户事件的内容。所有代码片段至代码片段的通信是通过相关联的活动完成。两个片段永远不应该直接通信。

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.
为了让一个代码片段来了通信的活动,您可以定义在代码片段类的接口,并在活动中实现它。该代码片段捕获接口实现其onAttach()的生命周期方法的过程中,并且可以然后调用接口方法,以便与活动通信。

Here is an example of Fragment to Activity communication:
这里是片段到活动通信的例子:

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    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
        // 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 mCallback instance of the OnHeadlineSelectedListener interface.
现在该片段可以通过调用使用OnHeadlineSelectedListener接口的mCallback实例onArticleSelected()方法(或在接口的其它方法)传送消息到活动。

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.
例如,在片段下述方法,当用户点击一个列表项被调用。该片段使用回调接口传递该事件到父活动。

@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Send the event to the host 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.
为了从该片段接收事件回调,活动托管它必须实现在片段类中定义的接口。

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

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
        // Do something here to display that article
    }
}

Deliver a Message to a 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.
主机活动可以通过捕获与findFragmentById()的代码片段例如消息传送给一个片段,然后直接调用该片段的公共方法。

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:
例如,假设上述显示的活动可以包含的用于显示由上述回调方法返回的数据所指定的项的另一个片段。在这种情况下,该活动可以通过在回调方法的其他片段,将显示该项目收到的信息:

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

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we‘re in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            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();
        }
    }
}

Next class: Saving Data
下一节课:保存数据

本文翻译自:https://developer.android.com/training/basics/fragments/communicating.html

时间: 2024-10-29 01:17:10

Android官方入门文档[18]与其他碎片通信的相关文章

Android官方入门文档[5]建立操作栏

Android官方入门文档[5]建立操作栏 Setting Up the Action Bar建立操作栏 This lesson teaches you to1.Support Android 3.0 and Above Only2.Support Android 2.1 and Above You should also read?Setting Up the Support Library 这节课教你1.仅支持Android3.0及以上2.支持Android2.1及以上 你也应该阅读?设置支

Android官方入门文档[1]创建一个Android项目

Android官方入门文档[1]创建一个Android项目 创建一个Android项目 这节课教你1.创建与Android Studio中的一个项目2.创建使用命令行工具项目 你也应该阅读?管理项目 Creating an Android Project This lesson teaches you to1.Create a Project with Android Studio2.Create a Project with Command Line Tools You should also

Android官方入门文档[17]构建灵活的UI

Android官方入门文档[17]构建灵活的UI Building a Flexible UI构建灵活的UI This lesson teaches you to1.Add a Fragment to an Activity at Runtime2.Replace One Fragment with Another You should also read?Fragments?Supporting Tablets and Handsets这节课教你1.在运行时新增一个片段给一个活动2.用另一片段

Android官方入门文档[16]创建一个Fragment代码片段

Android官方入门文档[16]创建一个Fragment代码片段 Creating a Fragment创建一个Fragment代码片段 This lesson teaches you to1.Create a Fragment Class2.Add a Fragment to an Activity using XML You should also read?Fragments 这节课教你1.创建一个Fragment代码片段类2.使用XML来添加一个Fragment代码片段给一个活动 你也

Android官方入门文档[3]构建一个简单的用户界面

Android官方入门文档[3]构建一个简单的用户界面 Building a Simple User Interface构建一个简单的用户界面 This lesson teaches you to1.Create a Linear Layout2.Add a Text Field3.Add String Resources4.Add a Button5.Make the Input Box Fill in the Screen Width You should also read?Layouts

Android官方入门文档[10]支持不同的屏幕

Android官方入门文档[10]支持不同的屏幕 Supporting Different Screens支持不同的屏幕 This lesson teaches you to1.Create Different Layouts2.Create Different Bitmaps You should also read?Designing for Multiple Screens?Providing Resources?Iconography design guide 这节课教你1.创建不同的布

Android官方入门文档[2]运行你的应用程序

Android官方入门文档[2]运行你的应用程序 Running Your App运行你的应用程序 This lesson teaches you to1.Run on a Real Device2.Run on the Emulator You should also read?Using Hardware Devices?Managing AVDs with AVD Manager?Managing Projects 这节课教你1.运行在真实设备2.运行在模拟器 你也应该阅读?使用硬件设备?

Android官方入门文档[6]添加Action按钮

Android官方入门文档[6]添加Action按钮 Adding Action Buttons添加Action按钮 This lesson teaches you to1.Specify the Actions in XML2.Add the Actions to the Action Bar3.Respond to Action Buttons4.Add Up Button for Low-level Activities You should also read?Providing Up

Android官方入门文档[8]重叠操作栏

Android官方入门文档[8]重叠操作栏 Overlaying the Action Bar重叠操作栏 This lesson teaches you to1.Enable Overlay Mode 1.For Android 3.0 and higher only 2.For Android 2.1 and higher 2.Specify Layout Top-margin You should also read?Styles and Themes 这节课教你1.启用重叠模式 1.对An