如何以编程方式将背景颜色设置为 table 布局中的按钮?

How to set background color to button in table layout programatically?

我正在制作井字游戏。我已经使用井字棋盘的按钮并动态设置 table 布局。 问题是,我无法设置按钮的背景 属性。 我的代码在这里。

TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE); 
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }

请指导我。提前致谢。

只需拨打:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( 
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(5, 5, 5, 5);
b.setLayoutParams(params);
b.setBackgroundColor(Color.GREEN); // From android.graphics.Color

尝试b.setBackgroundColor(Color.Green);

设置按钮宽度

b.setLayoutParams(新 LinearLayout.LayoutParams(10, 100));

R.color.red是一个ID(也是一个int),但不是颜色。

改用以下方法之一:

// If you're in an activity:
Button.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not: 
Button.setBackgroundColor(Button.getContext().getResources().getColor(R.color.red));

或者,或者:

Button.setBackgroundColor(Color.RED); // From android.graphics.Color

或者,为了获得更多专业技能:

Button.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB

您没有为新创建的 Button 提供 LayoutParams。添加:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);