How to implement click event on toolbar icon?

I want to switch activity when I click on the toolbar icon.

enter image description here

my code is:

Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setIcon(R.mipmap.ic_launcher);

and handled by clicking this type, but does not work:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent i = new Intent(MainActivity.this,SecondActivity.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

and XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/rel_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.project.www.simpleproject.activity.MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/mytoolbar"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:theme="@style/AppToolbar">

</android.support.v7.widget.Toolbar>

Is it possible, and if so, let me know thanks

+4
source share
2 answers

You can also use this without using Toolbar.

final ActionBar actionBar = getSupportActionBar();
 actionBar.setDisplayHomeAsUpEnabled(true);
 actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher);

Then

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent i = new Intent(MainActivity.this,SecondActivity.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
+4
source

Use this with yours getSupportActionBar:

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
0
source

Source: https://habr.com/ru/post/1668120/


All Articles