[英]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.