我在互联网上搜索了我的问题的解决方案,但一直未能找到,希望您能帮助我
我正在尝试在 android 中创建一个具有 2 个 Activity 的主细节流程应用程序,第二个 Activity 包含一个 fragment 。谁能告诉我当我在 fragment 的 EditText 字段中进行更改时如何同时更新 MainActivity() 中的值?我尝试过使用 Intent ,但是当两个 Activity 并排时,似乎效果不佳。
有什么建议吗?
最佳答案
您似乎处于以下环境中:
When A happens, it triggers B
因此,我建议您使用 EventBus您项目中的库。
安装很简单。首先,在 build.gradle 文件中添加以下代码:
compile 'org.greenrobot:eventbus:3.0.0'
其次,让我们看看我们要在代码中添加什么。
在您想要更改的 fragment 中:
/* When A happens */
myButton.setOnClickListener(new View.OnClickListener() { // complete entering the content, update it
EventBus.getDefault.post(MyUpdateEvent(myContent));
});
创建自定义类MyUpdateEven:
public class MyUpdateEvent{
private String myContent;
public MyUpdateEvent(String myContent) {
this.myContent = myContent;
}
public String getUpdateContent() {
return myContent;
}
}
在您想要更新的 Activity 中:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault.register(this); // add this code to monitor the update
}
/* It triggers B */
@Subscribe // don't forget to add @Subscribe
public void onEvent(MyUpdateEvent event){
// this is your custom method
myTextView.setText(event.getUpdateContent()); // do your update
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault.unregister(this); // when you leave this lifecycle, cancel the monitoring
}
}
EventBus 是一个很好的库,我在我的项目中经常使用它。 我想它可以解决你的问题。
关于java - ANDROID:更新主详细信息流程布局中另一个 Activity 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569577/