Search code examples
javaandroidandroid-studioandroid-layoutandroid-toolbar

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?


Solution

  • 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