Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass layout as a function argument

It's possibly a really simple question but I am stuck with this one.

I have a function which is called many times in my application. I want to refactor it but I don't know how to pass the value of findViewById as an argument.

Do you know how to do it, please?


public void configureToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.activitySettingsToolbar);
        mToolbar.setElevation(0);
        mToolbar.setTitle("");

        setSupportActionBar(mToolbar);
    }

EDIT:

So far, I can do this configureToolbar(Activity activity, Toolbar mToolbar) with this result:


public void configureToolbar(Activity activity, Toolbar toolbar) {
       toolbar= (Toolbar) findViewById(R.id.activitySettingsToolbar);
       toolbar.setElevation(0);
       toolbar.setTitle("");

       ((AppCompatActivity)activity).setSupportActionBar(toolbar);
   }

But if I want to change my layout, I need to be able to pass it as an argument :/

like image 248
Lena Avatar asked Dec 17 '22 16:12

Lena


2 Answers

you could potentially pass through the ID of the toolbar :

public void configureToolbar(int id) {
    mToolbar = (Toolbar) findViewById(id);
    mToolbar.setElevation(0);
    mToolbar.setTitle("");

    setSupportActionBar(mToolbar);
}

then you can call this with :

configureToolbar(R.id.yourToolbarId)// in your case this is R.id.activitySettingsToolbar or any other toolbar Id

After edit from OP :

 public void configureToolbar(Activity activity, int toolbarId) {
 Toolbar toolbar= (Toolbar) activity.findViewById(toolbarId);
   if(toolbar != null) { //credit to @Gabriele Mariotti, I missed this check
   toolbar.setElevation(0);
   toolbar.setTitle("");

   ((AppCompatActivity)activity).setSupportActionBar(toolbar);
 }
}

then you call this with :

configureToolbar(yourActivity, R.id.yourToolbarId)
like image 135
a_local_nobody Avatar answered Dec 21 '22 10:12

a_local_nobody


You can do something like:

private void setupToolbar(int resource){
    Toolbar toolbar = findViewById(resource);
    if (toolbar != null){
      //....
    }
}
like image 35
Gabriele Mariotti Avatar answered Dec 21 '22 09:12

Gabriele Mariotti