Ojiahao
Ojiahao

Reputation: 11

toolbar back arrow doesn't work

I create other activity and hope use toolbar back arrow to return main activity, but under code doesn't work, please help me.

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    mToolbar.setTitle(R.string.setting);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);  
    mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                System.out.println("??");
                finish();
                return true;

            }
            return true;
        }
    });

}

Upvotes: 1

Views: 2700

Answers (3)

Darksymphony
Darksymphony

Reputation: 2683

You should use this:

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

Upvotes: 0

MrEngineer13
MrEngineer13

Reputation: 38856

The Toolbar has a method for this, setNavigationOnClickListener. It allows you to listen for click events on the back arrow. Here is the documentation if you want to read more about the Toolbar.

 mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
   public void onClick(View v) {
            System.out.println("??");
            finish();
    }
});

Upvotes: 3

cyberlobe
cyberlobe

Reputation: 1783

Try This Method:

@Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
        case android.R.id.home:


            return true;

        }
            return (super.onOptionsItemSelected(menuItem));

        }

Upvotes: 9

Related Questions