Search code examples
androidandroid-studioandroid-toolbar

Is there a better way to write android toolbar repeated methodes rather than writing the same code in every activity


I have 3 activities, they all have a toolbar,they are all working fine,but all of them have a slight difference in their toolbar, so I had to write a lot of similar lines in every activity,is it possible to make a class for the toolbar custom xml layout the same as php ,in php when you make a header that is shared with all pages you program the header in a way that it dynamically changes depending on the page you are in,do note the code is working fine if they are separate my only problem is I want to keep my toolbar methods separate from my activity methods.


Solution

  • you can create you own toolbar that extends from android.support.v7.widget.Toolbar. like that

    public class YourToolbar extends android.support.v7.widget.Toolbar{
    
    public YourToolbar (Context context) {
        super(context);
        initViewComponents(context);
    }
    
    
    public YourToolbar (Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initViewComponents(context);
    }
    
    public YourToolbar (Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViewComponents(context);
    }
    private void initViewComponents(Context context) {
       //here the shared code between all activities
         if(context instanceof FirstActivity){
        //code fore just the first Acitivity
         }if(context instanceof SecondActivity){
          //code fore just the secondAcitivity
         }else if(context instanceof ThreardActivity){
          }
        //here the shared code between all activities
      }
     }
    

    in your xml views replace the default tolbar by yours

    in the ativities classes replace the default toolbar by yours