Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

user interface - Android - Back button in the title bar

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here

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;
}

That's it!

(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" />

And in your Activity

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...