【Android必备】与其他碎片进行通信(10)

概要


为了重用Fragment UI组件,您应该将它们构建为一个完全独立的模块化组件,以定义其自身的布局和行为。一旦定义了这些可重用片段,您可以将它们与一个活动相关联,并将它们与应用程序逻辑连接起来,以实现整体复合用户界面。

通常你会希望一个片段与另一个片段进行通信,例如根据用户事件更改内容。所有片段到片段的通信都是通过共享 ViewModel或通过相关的活动完成的。两个碎片不应该直接通信。

推荐的片段之间通信的方式是创建一个共享 ViewModel对象。这两个片段都可以通过其包含的Activity访问ViewModel。碎片可以更新ViewModel中的数据,并且如果使用LiveData新状态公开数据,只要它从ViewModel观察LiveData,就会将其推送到其他碎片。要了解如何实现这种通信,请阅读ViewModel指南中的“片段之间共享数据”部分 。

如果您无法使用共享ViewModel在碎片之间进行通信,则可以使用接口手动实现通信流。然而,这最终会导致更多的工作要实施,并且在其他碎片中不易重复使用。

定义一个接口


为了允许片段与其Activity交流,您可以在Fragment类中定义一个接口并在Activity中实现它。Fragment在其onAttach()生命周期方法中捕获接口实现,然后可以调用接口方法以便与Activity进行通信。

以下是片段到活动通信的示例:

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");
        }
    }

    ...
}

现在片段可以通过onArticleSelected()使用接口mCallback 实例调用方法(或接口中的其他方法)将消息传递给活动OnHeadlineSelectedListener。

例如,当用户单击列表项时,会调用片段中的以下方法。片段使用回调接口将事件传递给父活动。

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Send the event to the host activity
        mCallback.onArticleSelected(position);
    }

实现接口


为了接收来自片段的事件回调,承载它的活动必须实现在片段类中定义的接口。

例如,以下活动实现了上例中的接口。

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

将消息发送给片段


主机活动可以通过捕获Fragment实例将消息传递到片段findFragmentById(),然后直接调用片段的公共方法。

例如,假设上面显示的活动可能包含另一个片段,用于显示上述回调方法中返回的数据所指定的项目。在这种情况下,活动可以将回调方法中收到的信息传递给显示该项目的其他片段:

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();
        }
    }
}

要了解有关实施碎片的更多信息,请参阅 碎片。您还可以通过探索 相关示例应用程序来了解更多信息。

Lastest Update:2018.05.08

联系我

QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

公众号推荐:

【Android必备】与其他碎片进行通信(10)

转载于:https://blog.51cto.com/4789781/2122342

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值