如何使用Androidfragmentmanager传递变量 [英] How to pass variables with Android fragmentmanager

查看:88
本文介绍了如何使用Androidfragmentmanager传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的代码可以在内容框架中从一个片段切换到另一个片段.有没有一种简单的方法可以在以下代码中传递变量?

I have the following simple code to switch from one fragment to another in the content frame. Is there a simple way to pass variables in the following code?

FragmentManager fm = getActivity().getFragmentManager();

fm.beginTransaction().replace(R.id.content_frame, new TransactionDetailsFragment()).commit();

推荐答案

您可以使用Bundle:

You can use Bundle:

FragmentManager fm = getActivity().getFragmentManager();
Bundle arguments = new Bundle();
arguments.putInt("VALUE1", 0);
arguments.putInt("VALUE2", 100);

MyFragment myFragment = new Fragment();
fragment.setArguments(arguments);

fm.beginTransaction().replace(R.id.content_frame, myFragment).commit();

然后,您按以下方式检索:

Then, you retrieve as follows:

public class MyFragment extends Fragment {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            int value1 = bundle.getInt("VALUE1", -1);
            int value2 = bundle.getInt("VALUE2", -1);
        }
    }
}

这篇关于如何使用Androidfragmentmanager传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆