How to display and set click event on Back Arrow on Toolbar?

Viewed 100948

Back button on toolbar

How can I set back arrow in Android toolbar and also apply click listener?

7 Answers

Complete example here http://www.freakyjolly.com/how-to-add-back-arrow-in-android-activity/

Use getSupportActionBar() Activity on which you want to show Back Icon

In OtherActivity.class

public class OtherActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.other_activity);


    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

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

public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

}

This will add a event listen

Very simple code. Add inside onCreateView() method of activity

To display icon

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and to add click listener

 toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Put your click logic here
            }
        });
Related