[英]How to make home button act as back button?
I have two activities.One of them has Fragment. 我有两个活动,其中一个活动是Fragment。
From this fragment I can go to another activity, but by clicking the button "home" it goes to previous activity instead of going to the fragment of the previous activity. 从这个片段中,我可以转到另一个活动,但是通过单击按钮“ home”,它会转到上一个活动,而不是上一个活动的片段 。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_closet);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Refere below code : 请参考以下代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You need to override below method : 您需要重写以下方法:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
finish();
return true;
}
return false;
}
getSupportActionBar().setNavigationOnClickListener(new OnClickListener {
public void onClick(View v){
onBackPressed()
}
})
Since you want same behavior as of back
button you should use onBackPressed();
由于您希望获得与back
按钮相同的行为,因此应使用onBackPressed();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.