在Android中创建自定义后退按钮 [英] Creating custom back button in android
问题描述
我有一个具有菜单的应用程序,根据您在菜单中按的按钮,将打开一个新活动.我想在每个屏幕上都有一个后退按钮,将您带到上一个屏幕,所以我想知道如何解决这个问题?
I have an application that has a menu and depending on what button you press in the menu a new activity is opened. I want to have a back button on every screen that will bring you to the previous screen so I'm wondering how do I go about this?
这是我使用过的一些有效的代码:
Here is some code I have used that works:
backButton = (ImageButton) findViewById(R.id.back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
但是,对我来说,将此代码放入我的所有活动中并不是一种很好的编程习惯.我该如何创建某种堆栈来保存所有查看的页面,并使用该堆栈返回上一页?
However its not good programming practice for me to put this code in all my activities. How do I go about creating some kind of stack that saves all the pages viewed and using that to return to the previous page?
我必须在应用程序中放置一个后退按钮,这样我才能在ActionBar中使用现有按钮.
I have to put a back button in my application so I cannot use the existing one in the ActionBar.
推荐答案
您是否尝试过在活动中使用操作栏?在每项活动中使用
Have you tried using action bar in your activity ? use in every activity
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setTitle(getResources().getString(R.string.app_name));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.app_icon);
}
并处理
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
这篇关于在Android中创建自定义后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!