0
我有一個在代碼中創建的按鈕,該按鈕具有Click事件的偵聽器。每次單擊該按鈕時,都應該生成另一個按鈕並將其添加到原始按鈕下方。但是,無論點擊第一個按鈕多少次,它只會添加一次動態按鈕,而不會再添加。添加第一個按鈕後,在Android中動態添加按鈕不起作用
這裏是我的編碼:
public class DynaminControlActivity extends Activity {
private RelativeLayout container;
private int mainIdCnt = 0;
private int mainId = 100;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createMainButton();
}
public void createMainButton() {
container = (RelativeLayout) findViewById(R.id.workLayout);
Button b = new Button(this);
b.setId(mainIdCnt + mainId);
CharSequence text = "Main +";
b.setText(text);
container.addView(b);
if (mainId > 0) {
mainId++;
}
b.setOnClickListener((new View.OnClickListener() {
public void onClick(View v) {
createDynamicButton();
}
}));
}
public void createDynamicButton() {
container = (RelativeLayout) findViewById(R.id.workLayout);
Button b = new Button(this);
CharSequence text = "Main +";
b.setText(text);
RelativeLayout.LayoutParams relLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relLayout.addRule(RelativeLayout.BELOW, mainIdCnt + mainId);
container.addView(b, relLayout);
if (mainId > 0) {
mainId++;
}
}
我覺得你不需要設置ID到所有按鈕,android在創建按鈕時設置。嘗試刪除setid部分。 – Aracem
remove b.setId(MainIdCnt + MainId); 並再試一次。 – user370305
我面臨同樣的問題 – pas