How to implement click event on toolbar icon?
Asked Answered
S

2

8

I want to switch activity on click of toolbar icon.

enter image description here

my code :

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

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

and handled on click like this but its not working:

@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 yes, then let me know thankyou

Snuck answered 28/1, 2017 at 16:40 Comment(7)
try the solution before askingMonosepalous
I tried but its not working.Snuck
what's not workingMonosepalous
Try add getSupportActionBar().setDisplayShowHomeEnabled(true);Nameplate
still not working..Snuck
And also getSupportActionBar().setDisplayHomeAsUpEnabled(true);Nameplate
@MayurKharche check the answer manCatatonia
N
7

You can also have 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);
    }
}
Nameplate answered 28/1, 2017 at 17:3 Comment(2)
Solved, Thank youSnuck
yes, i replace icon with HomeAsUpIndicator and it works fine now.Snuck
C
0

Use this along with your getSupportActionBar:

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Catatonia answered 28/1, 2017 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.