传递程序生成按钮的重复属性



我正在为"循环"生成很多使用30"的按钮,几乎所有代码都相同。我想知道是否有可能以某种方式将我的" button.set"属性在我的外部"循环也将其传递给其他循环"。

   for (int i = 1; i < 4; i++) {
        Button button = new Button(this);
        button.setId(i);
        button.setLayoutParams(params);
        button.setTextColor(Color.parseColor("#ffffff"));
        button.setAllCaps(false);
        button.setTextScaleX(0.92f);
        button.setPadding(20, 20, 20, 20);
        button.setBackgroundColor(Color.parseColor("#70553B"));
        button.getBackground().setAlpha(20);
        button.setOnClickListener(this);
        button.setMaxLines(1);
        button.setGravity(Gravity.CENTER);
        buttonHolder[i] = button;
        side_a.addView(button);
    }

您可以创建一个函数,该函数可以使用按钮并将所有设置应用于它:

   public void setButtonParams(Button button){
        button.setTextColor(Color.parseColor("#ffffff"));
        button.setAllCaps(false);
        button.setTextScaleX(0.92f);
        button.setPadding(20, 20, 20, 20);
        button.setBackgroundColor(Color.parseColor("#70553B"));
        button.getBackground().setAlpha(20);
        button.setMaxLines(1);
        button.setGravity(Gravity.CENTER);
   }
   for (int i = 1; i < 4; i++) {
        Button button = new Button(this);
        button.setId(i);
        button.setLayoutParams(params);
        setButtonParams(button);
        button.setOnClickListener(this);
        buttonHolder[i] = button;
        side_a.addView(button);
    }

如果要设置依赖上下文的ID和其他值,则可以将它们作为参数添加到setButtonParams函数。

最新更新