mra*_*tor 30 android android-actionbar
我正在使用Actionbar和它的"向上"按钮从详细活动返回到主要活动,这很好.类似地,用户可以按下系统"后退"按钮返回主活动.
在我的主要活动中,onCreate()
数据从互联网下载,以便在应用程序启动时显示.我注意到当我使用Actionbar"向上"按钮从详细信息转到主要活动时,onCreate()
运行,重新下载数据.但是onCreate()
当我使用系统"后退"按钮时不运行,因此立即显示主要活动视图.
我在详细活动中用来实现"向上"按钮的代码是:
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
Run Code Online (Sandbox Code Playgroud)
我希望"向上"按钮的行为类似于"后退"按钮,而不是重新运行onCreate()
.但我不确定如何实现这一点,或者"后退"按钮实现返回主活动的代码路径.
谢谢!
dym*_*meh 49
而不是开始一个全新的活动,只需完成您所在的详细活动
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
Run Code Online (Sandbox Code Playgroud)
然后,您将返回活动堆栈上的上一个活动(您的主要活动),并且不应该调用onCreate
Kri*_*son 10
如果你想要完全按照Back做的话,你可以这样做:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)
请注意,onBackPressed()
只是调用的默认实现finish()
,但onBackPressed
可以重写.
我认为在这篇文章中可以找到更好的解决方案.
调用finish()
在特定情况下工作,但可能并不总是产生文档中描述的行为,例如:
通过电话
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
NavUtils.navigateUpTo(this, intent);
Run Code Online (Sandbox Code Playgroud)
您将返回到您离开状态的父活动.如果你有一个扁平的应用程序结构,它仍然会像后退按钮一样.
归档时间: |
|
查看次数: |
15405 次 |
最近记录: |