“Back button” using getSupportActionbar and appcompat v7 toolbar

前端 未结 8 594
时光取名叫无心
时光取名叫无心 2021-01-30 02:27

I\'m using the new toolbar from the Appcompat V7 library and I\'m making an application with navigation drawer and with fragments.

In some fragments I don\'t want to sho

8条回答
  •  -上瘾入骨i
    2021-01-30 02:55

    Not sure if this works in OP's case, but in many cases this is probably the simplest option to implement Back button with the AppCompat Toolbar.

    Skip all the setHomeButtonEnabled, setDisplayHomeAsUpEnabled and onOptionsItemSelected stuff, and related issues.

    Instead, when initialising the Toolbar, simply set 1) navigation icon and 2) navigation OnClickListener for it:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    
    if (enableBackNavigation) {
        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
    

提交回复
热议问题