How to pass layout as a function argument

Lena :

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 :/

a_local_nobody :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139305&siteId=1