在 1 行上动态加载 5 个按钮

Dynamically load 5 buttons on 1 row

我在使用此表格布局时遇到了一些困难,应该在 5 个按钮之后创建一个新行。当我添加 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 起作用? (请注意,我有“//”,因为它现在不工作,遮阳篷不是 "remove //")

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

我假设 lesson.getId(); returns id 的整数值。 setText() 需要一个字符串参数。你需要做 button.setText(String.valueOf(lesson.getId()));

希望对您有所帮助!