S
S
Sland Show2017-06-25 23:56:43
Android
Sland Show, 2017-06-25 23:56:43

How to create a back button in an ActionBar?

I want to make a button to return to the previous activity.
Like this:
65208ed974134dd9b31a4bd250968a54.png
And I was already able to get this button
a4f52d645eba4b30b147b753fff2fab5.png
1. Created a menu folder in the res folder
2. Created an xml file
Here is the file code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/id_profile_add"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Add" />
    <item
        android:id="@+id/id_delete_all"
        android:orderInCategory="101"
        android:showAsAction="never"
        android:title="Delete All" />

</menu>

Something like this happened
9ccb72ccf9c04ee0aedb9b818299911b.png
. And in the necessary activity, I added two methods.
The button is a4f52d645eba4b30b147b753fff2fab5.pngworking
@Override
public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
 int id = menuItem.getItemId();
 /* Как пример.
 * Функционал добавления записи в БД.
 */
 if (id == R.id.id_profile_add) {
...
 return true;
 }
 if (id == R.id.id_delete_all) {
...
 return true;
 }
 return true;
}

I also added this code:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and it seems that the necessary return button appeared on the action bar. But I don't know how to attach a listener to it :/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Gapchenko, 2017-06-26
@SlandShow

Attach a click handler to item with id android.R.id.home.
There is another option not to hang the handler, but to specify the parent activity in the manifest - then when you click on the up button, you will return to the parent activity without any additional code.

G
goodTimes, 2017-06-26
@goodtimes922

Why don't you like the Navigation Drawer ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question