繁体   English   中英

创建一个按钮并以编程方式将其添加到视图

[英]Create a button and add it to a view programmatically

我正在为 Android 创建一个流行的扫雷游戏版本。我正在尝试以编程方式创建一个按钮并将其添加到 RelativeLayout。 我在这里发现了一些非常相似的东西: How do I programmatically add buttons into layout one by one by 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是一个控件。

我认为您的屏幕是空白的,因为您尚未设置内容视图。 我的意思是代码做了它应该做的但是,你应该删除顶部的“setContentView()”方法并将它放在最后,然后你应该在关闭 onCreate() 之前将它设置为 RelativeLayout方法:像这样:

public void create() {
RelativeLayout layout1 = new RelativeLayout(this);
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(layout1);
   }

另请注意,我稍微更改了 Relativelayout 的声明。 我希望这有帮助。 :) !

您必须输入 RelativeLayout 的 ID,而不是 xml 文件名。 尝试使用 RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.yourRelativeLayoutViewID);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM