【问题标题】:How to pass layout as a function argument如何将布局作为函数参数传递
【发布时间】:2019-08-26 09:26:03
【问题描述】:

这可能是一个非常简单的问题,但我被这个问题困住了。

我有一个在我的应用程序中被多次调用的函数。 我想重构它,但我不知道如何将findViewById 的值作为参数传递。

请问你知道怎么做吗?


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

        setSupportActionBar(mToolbar);
    }

编辑:

到目前为止,我可以通过 configureToolbar(Activity activity, Toolbar mToolbar) 执行此操作,结果如下:


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

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

但是如果我想改变我的布局,我需要能够将它作为参数传递:/

【问题讨论】:

  • configureToolbar(Toolbar mToolBar) ?并通过configureToolbar((Toolbar)findViewById(R.id.x))调用它
  • 创建这样的函数configureToolbar(Toolbar toolBar){ // function body}
  • @AbidKhan 这是 java,不是 kotlin

标签: java android android-layout arguments


【解决方案1】:

您可能会通过工具栏的 ID:

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

    setSupportActionBar(mToolbar);
}

然后你可以调用它:

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

从 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);
 }
}

然后你调用它:

configureToolbar(yourActivity, R.id.yourToolbarId)

【讨论】:

    【解决方案2】:

    你可以这样做:

    private void setupToolbar(int resource){
        Toolbar toolbar = findViewById(resource);
        if (toolbar != null){
          //....
        }
    }
    

    【讨论】:

      【解决方案3】:

      在参数中传递布局的最佳方式是使用@LayoutRes注解:

      fun buildDialog(@LayoutRes viewId : Int) {
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 2016-07-23
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多