Saloni
Saloni

Reputation: 172

Back button as Menu in fragment

I want to add a back button as menu in the left of the action bar in fragment. But I don't want the back arrow as my icon.

actionBar.setDisplayHomeAsUpEnabled(true);

The above code line gives the back arrow symbol. Instead i want to use some custom image. Also using that custom image should get it back to its previous activity.

Upvotes: 2

Views: 2234

Answers (2)

Suhayl SH
Suhayl SH

Reputation: 1223

Add this to your theme in styles.xml:

<item name="android:homeAsUpIndicator">@drawable/my_icon</item>

It will override the default icon. By default it uses the following id:

android.R.id.home

You can use this id to navigate back to your previous activity:

View homeView = getActionBar().getCustomView().findViewById(android.R.id.home);
        homeView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v)
            {
                //Go back
            }
        });

or

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        //Return back to your activity!
        return true;
    }
    return super.onOptionsItemSelected(item);
}

For more information check the official documentation at : https://developer.android.com/training/implementing-navigation/ancestral.html

Upvotes: 0

Saloni
Saloni

Reputation: 172

I added something like:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            getActivity().onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }

}

It worked for me.

Upvotes: 2

Related Questions