Android中的显示网格问题

时间:2019-05-17 21:22:54

标签: java android

我尝试在Android中以编程方式显示5x5按钮网格。但是它并不能显示所有的网格

XML代码:

<LinearLayout
        android:id="@+id/mainTableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>

Java代码:

LinearLayout mainTable = findViewById(R.id.mainTableLayout);

    for(int i = 0; i < COUNT_COLUMS; i++) {

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

        for (int j = 0; j < COUNT_COLUMS; j++) {
            Button button = new Button(this);
            linearLayout.addView(button);
        }

        mainTable.addView(linearLayout);
    }

2 个答案:

答案 0 :(得分:1)

这应该有效:

LinearLayout mainTable = findViewById(R.id.mainTableLayout);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int DeviceTotalWidth = metrics.widthPixels;
    int with = DeviceTotalWidth / 5;

    for (int i = 0; i < 5; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        row.getWeightSum();
        for (int j = 0; j < 5; j++) {
            Button btnTag = new Button(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams(with, LinearLayout.LayoutParams.WRAP_CONTENT));
            btnTag.setText("" + (j + 1 + (i * 5)));
            btnTag.setId(j + 1 + (i * 5));
            row.addView(btnTag);
        }

        mainTable.addView(row);
    }

但是更好的方法是使用GridLayout

答案 1 :(得分:0)

您可以使用RecyclerView来代替以编程方式在linearlayout中添加按钮。将GridLayoutManager的RecyclerView与跨度计数5和垂直方向一起使用。