android - 抽屉导航中 fragment 之间的通信

标签 android android-fragments

我正在尝试在单击按钮时将数据从 Fragment A 发送到 NAVIGATION Drawer 的 Fragment B。我尝试使用 bundle 和 intent,但它们都不起作用。

在 Fragment A 中,我有 editText 和按钮,当我点击时,数据被传递到另一个 fragment。

在 fragment B 中有 textView,其中将显示 editText 数据,但我无法在抽屉导航中的 fragment 之间进行通信

最佳答案

从第一个 fragment 启动 fragment 时

Bundle bundle = new Bundle();
bundle.putString("key", YOUR_EDITVIEW_TEXT);

Fragment fragment = new SECONDFragment();

if (arguments != null) {
    fragment.setArguments(arguments);
}

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack("");
ft.commit();

并且在SecondFragment

private String mData;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mData = getArguments().getString("key");
    }


}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.YourLayout, container, false);

    TextView text = (TextView) rootView.findViewById(R.id.yourTextView);
    text.setText(mData);
    return rootView;
}

关于android - 抽屉导航中 fragment 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064874/

相关文章:

java - Android:如何在内存中创建和保存 map View 以供所有 Activity 使用

android - 安卓编码标准

android - fragment 的 savedInstanceState 是否与父 Activity 的 savedInstanceState 共享?

android - 如何通过android中的ksoap SoapObject检索来自webservice的复杂类型对象

Android Gradle 插件 : Create AAR with Jar Dependencies and Proguard

android - fragment 真的需要一个空的构造函数吗?

android - java.lang.NullPointerException : Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

android - 登录后如何获取 fragment 的当前用户ID

android - Facebook 的应用邀请错误

java - vector 仅填充最后一项