Android:将值从容器 Activity 传递到其 fragment

标签 android android-fragments

我的代码包含一个主 Activity 和其中的三个 fragment ,我想将一个值从容器 Activity 传递到其 fragment ,但它不起作用。
我试图制作一个接口(interface)来相互通信,但什么也没发生。
我也尝试制作 bundle ,但在 setArguments 中出现错误。

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

并在 fragment 中

Bundle bundle = this.getArguments();
if(bundle != null){
    int i = bundle.getInt(key, defaulValue);
}

你能帮我一下吗? 谢谢!

最佳答案

尝试在您的 Activity 中使用 Intent :

Intent a = new Intent (this, yourfragment.class);
a.putInt(key, value);
setIntent(a);

在你的 fragment 中:

ActivityName activity = (ActivityName) getActivity();
Intent b= activity.getIntent();    
int Uid = b.getIntExtra(key);

关于Android:将值从容器 Activity 传递到其 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19894681/

相关文章:

java - 为什么 getActionView() 返回 null

android - Eclipse 不显示 Genymotion 模拟器列表

android - 如何在 fragment 和 RecyclerView Adapter 之间建立接口(interface),以便从 fragment 获取 onActivityResult()

android - 在平板电脑的 Android 应用程序中获取外部存储路径

android - 第一次将当前值设置为 EditTextPreference

android - 动态更改 TabLayout 内的 fragment

android - 如何运行 chrome 工具而不是浏览器

Android在 fragment 和对话框 fragment 之间共享ViewModel?

java - 从 Cordova 插件在服务中启动 Vitamio

java - 检测主要 Activity 中 fragment 的 onclick