“findViewById”和“new View(content)”之间的区别

时间:2017-05-28 15:19:44

标签: java android

我正在尝试使用以下代码创建一个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);

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

另外我的content_grid.xml文件如下:

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

1 个答案:

答案 0 :(得分:0)

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

相关问题