动态加载1行的5个按钮

时间:2016-04-04 12:01:57

标签: java android tablelayout

我对这个tablelayout有一些困难,它应该在5个按钮之后创建一个新的Row。当我添加button.setText(lesson.getId());

时,它也会崩溃

LesSelectionActivity.java

    public static final int LESSON_ROW_COUNT = 5;

    public void setButtonLessons() {

    //draw LesSelection
    setContentView(R.layout.activity_drumles);

    TableLayout layout = (TableLayout) findViewById(R.id.les_select_layout);

    int buttonIdCounter = 0;
    for (Lesson lesson : getArrayLesson()) {
        int columnCounter = 0;

        TableRow tr = new TableRow(this);
        TableRow.LayoutParams params = new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
        params.setMargins(30, 0, 30, 0);
        tr.setLayoutParams(params);
        layout.addView(tr);

            if (columnCounter % LESSON_ROW_COUNT == 0) {
                tr = new TableRow(this);
                params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT);
                params.setMargins(30, 0, 30, 0);
                tr.setLayoutParams(params);
                layout.addView(tr);
            }

            Button button = new Button(this);

            button.setId(buttonIdCounter);

          //button.setText(lesson.getId());

            button.setOnClickListener(this);
            button.setBackgroundResource(R.drawable.buttonsoranje);
            TableRow.LayoutParams paramsRow = new TableRow.LayoutParams(
                    TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);

            paramsRow.column = columnCounter % LESSON_ROW_COUNT;
            params.gravity = Gravity.CENTER_HORIZONTAL;


            tr.addView(button);

            buttonIdCounter++;
            columnCounter = (columnCounter + 1) % LESSON_ROW_COUNT;
        }

    }

那么,为什么setText不起作用但setBackgroundResource呢? (注意我有“//”它,因为它现在不工作,awnser不是“删除//”)

为什么每行只有一个按钮?

1 个答案:

答案 0 :(得分:2)

我假设lesson.getId();返回id的整数值。 setText()需要String参数。您需要执行button.setText(String.valueOf(lesson.getId()));

希望这有帮助!