Abhay Koradiya
Abhay Koradiya

Reputation: 2117

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

I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically. Problem is that, I can't set background property of the button. My code is here.

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

Please guide me. Thanks in Advance.

Upvotes: 1

Views: 1060

Answers (4)

rafsanahmad007
rafsanahmad007

Reputation: 23881

Just call:

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

Upvotes: 0

Vijay Ankith
Vijay Ankith

Reputation: 72

Try b.setBackgroundColor(Color.Green);

set button width

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

Upvotes: 0

RonTLV
RonTLV

Reputation: 2556

You are not giving LayoutParams to your newly created Button. Add this:

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

Upvotes: 1

Vlad Ivchenko
Vlad Ivchenko

Reputation: 572

R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

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

Or, alternatively:

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

Or, for more pro skills:

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

Upvotes: 2

Related Questions