How to make the actionBar back button work?

Asked

Viewed 1,229 times

0

I’m not getting it to work. Help me. My manifest is like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alinesilvagonzaga.testedostrespontinhos">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Main2Activity"
        android:label="page two"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
        />

    </activity>
</application>

</manifest>

And the method to verify that it was touched:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
     }
      return super.onOptionsItemSelected(item);
  }

2 answers

3

Use the method setNavigationIcon to add the icon in the Toolbar and setNavigationOnClickListener to perform an action by clicking on the icon.

Method with support to Java 8 qualified

    applicationToolbar.setNavigationIcon(R.drawable.ic_close_26dp);
    applicationToolbar.setNavigationOnClickListener(view -> finish());

Observing: the lambda method view->finish() only works if you have Java 8 enabled.

Method with versions after the Java 8

    applicationToolbar.setNavigationIcon(R.drawable.ic_close_26dp);
    applicationToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ação desejada...

            }
        });

0


Create an Intent for the home case Example:

android case.R.id.home: Intent Intent = new Intent(Main2activity this, Mainactivity.class); startActivity(); Return true; Return true;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.