如何设置表格布局中每个第二个按钮的背景?

时间:2014-05-31 10:53:27

标签: android android-layout layout android-tablelayout

我在程序中动态制作了一个按钮网格,我以前做过这个TableLayout,这是我的代码:

    private void createLayoutDynamically() {
        won = (TableLayout)findViewById(R.id.won);

        for ( int qq = 1; qq < a; qq++) {
            TableRow tableRow = new TableRow(this);
            tableRow.setLayoutParams(new TableLayout.LayoutParams(

                    TableLayout.LayoutParams.MATCH_PARENT,
                    TableLayout.LayoutParams.MATCH_PARENT,
                    2
                    ));

            won.setPadding(25,25,25,25);
            won.addView(tableRow);

        for ( int q = 1; q < b; q++) {

            myButton = new Button(this);

            tableRow.setLayoutParams(new TableRow.LayoutParams(
                    TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.MATCH_PARENT,
                    2
                    ));
}
}
}

此代码的结果如下:

http://i.stack.imgur.com/Uli6s.jpg

我想实现这些按钮的背景每秒都会改变,如下所示:

http://i.stack.imgur.com/sVKXe.jpg 你可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

填充表格行时添加到循环中:

for ( int q = 1; q < b; q++) {
    myButton = new Button(this);
    int drawable = R.drawable.first_button;
    if (q%2 == 0) {
        drawable = R.drawable.second_button;
    } 
    myButton.setBackground(getResources().getDrawable(drawable)); //you can put Resources to variable and put it outside the loop
    tableRow.setLayoutParams(new TableRow.LayoutParams(
        TableRow.LayoutParams.MATCH_PARENT,
        TableRow.LayoutParams.MATCH_PARENT,
        2));
}