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

前端 未结 7 1052
-上瘾入骨i
-上瘾入骨i 2020-12-02 18:31

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

7条回答
  •  攒了一身酷
    2020-12-02 18:44

    If you want to know when home is clicked is an AppCompatActivity then you should try it like this: Use this code :

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

    Listen for click events on android.R.id.home like usual:

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
             Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
             startActivity(intent);
             finish();
        }
        return super.onOptionsItemSelected(menuItem);
    }
    

提交回复
热议问题