简体   繁体   中英

What is the best way to add a back button to custom toolbars?

So i know how to add a backwards navigation button to my custom toolbar, however there must be a more efficient way to add the functionality to multiple activities than copying and pasting this code in each one...

        Toolbar toolbar = findViewById(R.id.tlbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

I've tried making a common class were i create a function that could be called in each activity however you need to findViewById which can only be done in the activity. Any suggestions around this?

First Create a base class like this

public class BaseActivity extends AppCompatActivity{


    public  void setToolbar(@IdRes int toolbarID){
        try {
            Toolbar toolbar = findViewById(toolbarID);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }catch (Exception e){
            e.printStackTrace();

        }

    }

}

After extends all Activity class with BaseActivity class

public class LoginNewActivity extends BaseActivity{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbar(R.id.toolbar); //You can call your method like this
    }
}

If you want to know more about this do search for Inheritance and polymorphism in JAVA

in your activity tag on manifest add parentactivityname and add value as an activity which you want to go when back pressed.this is the best solution for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM