java - 创建一个按钮并以编程方式将其添加到 View 中

标签 java android android-layout

我正在创建流行的扫雷游戏的 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/

相关文章:

java - Java 的 hashCode 可以为不同的字符串产生相同的值吗?

java - 观察完成后在 View 中显示 AlertDialog

Android fragment 布局问题(垂直和水平居中按钮)

Android:如何指定 <layer-list> 的不透明度?

java - Viewpager 中的 fragment 仅在从旁边的 fragment 打开时刷新

java - 流收集与 map 收集

java - Android:从服务 Intent 中获取额外信息?

java - 如何实现其泛型模板扩展另一个接口(interface)的泛型接口(interface)?

java - 如何在android中使用对象模型数据库获取日期和月份列

android - IBM Worklight - 如何更改默认的 "Worklight Settings"字符串?