Android:检测活动何时返回到上一个活动
我有一个带有listView的活动A,用户单击启动活动B的任何项目。根据用户在活动B中所做的操作,可能会更改活动A上的listViewAndroid:检测活动何时返回到上一个活动,android,Android,我有一个带有listView的活动A,用户单击启动活动B的任何项目。根据用户在活动B中所做的操作,可能会更改活动A上的listView @Override protected void onResume() { super.onResume(); //Code to refresh listview } 因此,我的问题是: 当用户从活动B返回到活动A时,我如何告诉活动A它已恢复 我希望能够在活动a中的listView返回到时发出刷新的信号 谢谢 使用startActivityF
@Override
protected void onResume() {
super.onResume();
//Code to refresh listview
}
因此,我的问题是:
当用户从活动B返回到活动A时,我如何告诉活动A它已恢复
我希望能够在活动a中的listView返回到时发出刷新的信号
谢谢 使用startActivityForResult启动B活动。并在ActivityResult()方法上检查活动B中的数据。使用notifyDataSetChanged对listView更新内容。您可以在活动A的
onResume()
中添加代码以刷新listView
@Override
protected void onResume() {
super.onResume();
//Code to refresh listview
}
使用
startActivityForResult
是最优雅的方法<每次关闭和打开应用程序时,都会出现code>OnResume,这会占用更多的资源,尤其是在刷新大量数据的情况下
在活动顶部将请求代码声明为常量:
public static final int OPEN_NEW_ACTIVITY = 123456;
Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, OPEN_NEW_ACTIVITY);
将此放置在开始新活动的位置:
public static final int OPEN_NEW_ACTIVITY = 123456;
Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, OPEN_NEW_ACTIVITY);
当活动结束时做些什么。文档建议您使用resultCode
,但根据情况,按下按钮时,您的结果可以是result\u OK
或result\u cancelled
。所以我就不提了
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OPEN_NEW_ACTIVITY) {
// Refresh your ListView here
// ....
}
}
出于某种原因,我在把它放进碎片时遇到了麻烦。因此,您必须将其放在活动中。我有另一种方法来做这件事,在某些情况下可能会很方便-我保留private Bundle变量,让我们称之为
state
,当我启动一个活动时,我会放一个字符串,说明我启动了哪个活动:
state.putString("startedActivity", "A");
Intent intent = new Intent(this, ActivityA.class);
startActivity(intent);
我存储状态包以保持设备更改(旋转等):
在onCreate
中,我加载状态:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
savedInstanceState = new Bundle();
}
state = savedInstanceState;
}
然后在onResume
方法中,我可以检查我是否正在参加某个活动。请注意,我立即将该字符串从状态中移除,因此它不会在旋转更改时再次显示
public void onResume() {
super.onResume();
if (state.getString(STARTED_ACTIVITY, null) != null) {
// we just came from another activity!
state.putString(STARTED_ACTIVITY, null); // clear the state
// do whatever you need
}
}
嗯,我这样做了,效果很好,但实际上@Muz的答案也一样,而且更简单,所以如果你需要知道你是否真的从子活动中返回,那么就使用他的答案。注意,在其他情况下,例如活动开始、设备旋转等,这也被调用,而不仅仅是从活动B返回。