gpt4 book ai didi

java - 创建按钮网格

转载 作者:行者123 更新时间:2023-11-30 03:06:33 24 4
gpt4 key购买 nike

对不起,我问了一个如此愚蠢的问题,但我无能为力,这真的让我很烦。实际上,我正在尝试完全按照一个教程中的内容进行操作,但可能我没有正确复制代码。我想要做的是使用表格布局的 4x4 按钮网格。这是我的 xml Activity :

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Field"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableLayout>

这是我的java代码:

    public class Pokus extends Activity{

public void onCreate(Bundle savedInstanceState) {
TableLayout field = (TableLayout)findViewById(R.id.Field);
Button but[][] = new Button[4][4];
for(int i = 1; i!=5; i++){
TableRow tr = new TableRow(this);
for(int r = 1; r!=5; r++){
tr.addView(but[i][r]);
}
field.addView(tr);
}
setContentView(R.layout.activity_pokus);
}}

有没有人明白,哪里错了?

最佳答案

在你做任何事情之前设置内容 View 。这应该放在 onCreate 方法的开头:

 super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokus);

楼上的评论也是对的;从 0 开始 i:

for(int i = 0; i<4; i++){
TableRow tr = new TableRow(this);
for(int r = 1; r<4; r++){
tr.addView(but[i][r]);
}
field.addView(tr);
}

按钮但是[][] = new Button[4][4];-- 你还没有初始化数组中的按钮。在你写的循环之前先用这个迭代地遍历它:

for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
but[i][j] = new Button();

这将解决您的 NullPointerException

^ 与其做所有这些,不如根本不使用数组,简单地说:

for(int i = 0; i<4; i++){
TableRow tr = new TableRow(this);
for(int r = 1; r<4; r++){
tr.addView(new Button()); // new Button() instead of but[i][j]
}
field.addView(tr);
}

关于java - 创建按钮网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com