Fragments之间的交互

  • 为了重用Fragment UI组件,你应该把每一个fragment都构建成完全的自包含的、模块化的组件,定义他们自己的布局与行为。当你定义好这些模块化的Fragments的时,你就可以让他们关联acticvity,使他们与application的逻辑结合起来,实现全局的复合的UI。

  • 经常地,你想fragment之间能相互交互,比如基于用户事件改变fragment的内容。所有fragment之间的交互需要通过他们关联的activity,两个fragment之间不应该直接交互。

定义一个接口

  • 为了让fragment与activity交互,你可以在Fragment 类中定义一个接口,并且在activity中实现这个接口。Fragment在他们生命周期的onAttach()方法中捕获接口的实现,然后调用接口的方法来与Activity交互。
下面是一个fragment与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");
        }
    }

    ...
}

  • 现在Fragment就可以通过调用OnHeadlineSelectedListener接口实例的mCallback中的onArticleSelected()(也可以是其它方法)方法与activity传递消息。

  • 举个例子,在fragment中的下面的方法在用户点击列表条目时被调用,fragment 用回调接口来传递事件给父Activity.

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

实现接口

  • 为了接收回调事件,宿主activity必须实现在Fragment中定义的接口。

举个例子,下面的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
        // Do something here to display that article
    }
}

传递消息给Fragment

  • 宿主activity通过findFragmentById()方法来获取fragment的实例,然后直接调用Fragment的public方法来向fragment传递消息。

  • 例如,想象一下,上面所示的activity可能包含另外一个fragment,这个fragment用来展示从上面的回调方法中返回的指定的数据。在这种情况下,activity可以把从回调方法中接收到的信息传递给这个展示数据的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
        // 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();
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: "Unknown fragments"错误通常是由于在XML布局文件中引用了未定义的片段(fragment)而导致的。根据引用\[1\]中的信息,使用v4包的fragment时,XML布局文件的根节点应该使用FrameLayout而不是fragment。请确保你的XML布局文件中的根节点是FrameLayout,并且在代码中正确加载和管理片段。另外,根据引用\[2\]和引用\[3\]中的代码示例,你需要创建对应的PM_Fragment和LM_Fragment类,并在这些类中实现onCreateView方法来加载对应的布局文件。确保你的代码中没有引用未定义的片段,并正确加载和管理片段,这样就可以避免"Unknown fragments"错误的出现。 #### 引用[.reference_title] - *1* [xml中用fragment出现Error inflating class fragment的问题解决方案](https://blog.csdn.net/u013899706/article/details/43273889)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Android Fragments](https://blog.csdn.net/LGGisKing/article/details/45463505)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值