我有一个应用程序,片段之间有标签导航。其中一个片段可以选择打开一个新活动。当我使用此活动中的内置设备后退按钮时,它会返回选项卡式活动,并选择上一个片段选项卡。
我已使用以下方法在我的应用中的活动操作栏中添加了一个后退按钮:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
并在清单中设置父活动,但此按钮始终导航回父活动的第一个标签,而不是先前可见的标签。
如何使这个后退按钮的行为与设备后退按钮相同?
答案 0 :(得分:4)
做这样的事情:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
onBackPressed()方法:
@Override
public void onBackPressed() {
super.onBackPressed();
}
答案 1 :(得分:0)
以这种方式处理事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
采用背压法
@Override
public void onBackPressed() {
Intent intent = new Intent(SecondActivity.this,TabbedActivity.class);
intent.putExtra("IsBack",true);
startActivity(intent);
}
在标签式活动中
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
if(getIntent().getExtras().getBoolean("IsBack")){
//navigate to your desire fragment
}
}