Android - 标题栏中的后退按钮 [英] Android - Back button in the title bar
问题描述
在许多应用程序(日历、云端硬盘、Play 商店)中,当您点击按钮并输入新活动时,标题栏中的图标会变成后退按钮,但对于我正在制作的应用程序,它不会那.我如何让那个图标带你回到上一个屏幕?
In many apps (Calendar, Drive, Play Store) when you tap a button and enter a new activity, the icon in the title bar turns into a back button, but for the app I am making, it doesn't do that. How do I make that icon take you back to the previous screen?
推荐答案
在标题栏中创建后退按钮有两个简单的步骤:
There are two simple steps to create a back button in the title bar:
首先,在要在其标题栏中添加后退按钮的活动中使用以下代码使应用程序图标可点击:
First, make the application icon clickable using the following code in the activity whose title bar you want to have a back button in:
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
添加上述代码后,您将看到应用程序图标左侧出现一个后退箭头.
After you have added the above code, you will see a back arrow appear to the left of the application icon.
其次,在完成上述操作后,您仍然需要创建代码来利用点击事件.为此,请注意,当您实际单击应用程序图标时,会调用 onOptionsItemSelected
方法.因此,要返回上一个活动,请将该方法添加到您的活动中,并在其中放入 Intent
代码,以便您返回上一个活动.例如,假设您尝试返回的活动称为MyActivity
.回过头来,写方法如下:
Second, after you have done the above, you still have to create code that will take advantage of the click event. To do so, be aware that, when you actually click on the application icon, an onOptionsItemSelected
method is called. So to go back to the previous activity, add that method to your activity and put Intent
code in it that will return you to the previous activity. For example, let's say the activity you are trying to go back to is called MyActivity
. To go back to it, write the method as follows:
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MyActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
就是这样!
(在 Android 开发人员 API 中,它建议弄乱清单并添加诸如 android:parentActivityName
之类的东西.但这似乎对我不起作用.以上更简单,更可靠.)
(In the Android developers API, it recommends messing around with the manifest and adding stuff like android:parentActivityName
. But that doesn't seem to work for me. The above is simpler and more reliable.)
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
在你的活动中
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
这篇关于Android - 标题栏中的后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!