Android 单击ActionBar中的后退按钮时,不会调用onActivityResult
我的问题是:Android 单击ActionBar中的后退按钮时,不会调用onActivityResult,android,android-actionbar,onactivityresult,Android,Android Actionbar,Onactivityresult,我的问题是: 创建一个主活动。添加一个按钮,该按钮将启动另一个活动SecondActivity Intent i = new Intent(getActivity(),SecondActivity.class); startActivityForResult(i,0); 在SecondActivity中,我捕获了back button click事件,还添加了一个按钮以返回到第一个活动 单击操作栏中的“后退”按钮时: Button btn = (Button)
Intent i = new Intent(getActivity(),SecondActivity.class);
startActivityForResult(i,0);
Button btn = (Button)this.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
@凌驾
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// back button
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
setResult(Activity.RESULT_OK, resultIntent);
//finish();
return false;
}
return super.onOptionsItemSelected(item);
}
单击“活动”中的按钮时:
Button btn = (Button)this.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
当我单击SecondActivity中的按钮时,会调用MainActivity中的onActivityResult,但如果我单击SecondActivity的Actionbar中的back按钮,则不会调用它。有人能告诉我为什么吗?谢谢以下是有效的代码:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// back button
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
我猜finish()将关闭当前活动,并返回true,告知操作已被处理。(默认的后退操作似乎与finish()不同。)尝试以下操作:-
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
好答案是。这对我有用。这是他的解决方案的副本:
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent result = new Intent((String) null);
result.putExtra("SOME_CONSTANT_NAME", true);
setResult(RESULT_OK, result);
finish();
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}
在OnOptions ItemSelected()中取消对finish()的注释并重试一次…我尝试了使用finish()或不使用finish()。两者都不起作用。'return true;'是该问题的真正关键词。如果您没有注意到这一点,应用程序将无法正常关闭。如果我在OnOptions ItemSelected中返回false,将触发MainActivity中的onCreate事件。已重新创建主活动。我想这就是为什么onActivityResult从未被调用的原因。我想这与我自己的答案是一样的。finish()和onBackPressed()之间有什么区别吗?@bagusflyer这对我来说很有效,所以你可能会考虑……但值得一试。