有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

“findViewById”和“新视图(内容)”之间的java差异

我正在尝试使用以下代码创建一个3x4的按钮网格:

public class Grid extends AppCompatActivity {

    LinearLayout myLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_grid);
        myLayout = (LinearLayout) findViewById(R.id.content_grid);
        for (int i = 0; i < 3; i++) {
            LinearLayout row = new LinearLayout(this);
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btn = new Button(this);
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btn.setLayoutParams(btnParams);
                btn.setText(" " + (j + 1 + (i * 4)));
                btn.setId(j + 1 + (i * 4));
                row.addView(btn);
            }
            myLayout.addView(row);
        }
    setContentView(myLayout);;
}

}

这段代码工作得非常好,并且创建了我想要的网格,但是如果我更改了线

myLayout = (LinearLayout) findViewById(R.id.content_grid);

myLayout = new LinearLayout(this);

然后只生成网格的第一行,而不是第二行和第三行。我想知道为什么会这样

是否在线

setContentView(R.id.content_grid);

在第二种情况下,是否存在似乎没有什么区别

此外,我的内容网格。xml文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:orientation="vertical"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:id="@+id/content_grid"
</LinearLayout>

共 (1) 个答案

  1. # 1 楼答案

    默认情况下LinearLayout将方向设置为水平。尝试将方向垂直于myLayout设置一个LayoutParams