有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我用多达30个“for”循环生成了很多按钮,几乎所有的代码都是相同的。 我想知道是否有可能以某种方式将我的“button.set”属性从我的“for”循环之外传递给其他循环

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

共 (1) 个答案

  1. # 1 楼答案

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

       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函数中