我正在创建流行的扫雷游戏的 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);
}
提前感谢您的回复
最佳答案
已通过 setContentView(R.layout.xxxx)
设置 Activity 的布局 xml ?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
...
这个
RelativeLayout layout1 = (RelativeLayout) findViewById(R.layout.game);
应该是
RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.relative_id);
R.id...
用于映射控件,RelativeLayout是一个控件。
关于java - 创建一个按钮并以编程方式将其添加到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10088490/