【发布时间】:2012-04-10 12:07:45
【问题描述】:
我正在为 Android 开发流行的扫雷游戏版本。我正在尝试以编程方式创建一个按钮并将其添加到RelativeLayout。我在这里发现了一些非常相似的东西:How do I programmatically add buttons into layout one by one in several lines?
当我尝试运行它时,我在以下位置收到 NullPointerException:
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
这是整个代码块:
public void create() {
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
for(int i = 0; i < gridSize; i++) {
if(grid[i] == 0) { //if grid pos. indicates an empty cell
Button empty = new Button(this);
empty.setBackgroundResource(R.drawable.emptybutton); //set background to empty
empty.setId(i); //set id to value of i
empty.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout1.addView(empty); //add the button to the relativeLayout view
//((Button) findViewById(i)).setOnClickListener(emptyListener);
}
提前感谢您的任何回复
【问题讨论】:
-
我认为您的问题无法到达您的 game.xml 。你能提供你的结构(大纲)吗?
-
我正在使用整数数组来模拟扫雷字段。例如,位置 [2] 处的值 9 表示扫雷区域的位置 2 处有地雷。然后我使用 if 语句生成不同的按钮,即如果 position[2] == 9 将创建一个代表地雷的按钮。我正在尝试将这些按钮添加到代表扫雷字段的相对布局中。这有帮助吗?
标签: java android android-layout