3 回答

TA貢獻1900條經(jīng)驗 獲得超5個贊
這是因為在將按鈕添加到布局后,您將啟動新的 Activity,無論它是同一個 Activity。每當(dāng)創(chuàng)建活動時,它將始終使用初始 xml 格式。我認(rèn)為您的印象是添加新按鈕將持續(xù)存在并成為 XML 的一部分。如果你想開始新的活動,那不是真的。在 Bundle 中設(shè)置新的 Button 值,然后在 onCreate 檢查 bundle 的存在。如果存在,則添加一個新按鈕。
int buttonId = -1;
protected void onCreate(Bundle b){
//set the layout related stuff first
Bundle b = getIntent().getExtras();
if(b!= null && (b.getInt(NEW_BUTTON_KEY, -1)!=-1)){
buttonPanel = (LinearLayout)findViewById(R.id.LinearButtonPanel);
for(int i = 0; i< b.getInt(NEW_BUTTON_KEY, -1); i++)
Button newButton = new Button(this);
newButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newButton.setId(i);
newButton.setText("Button " + i);
buttonPanel.addView(newButton);
}
}
順便說一下,你為什么要進行新的活動?只需在同一個活動中添加按鈕,否則您的活動堆棧將隨著每個級別變得龐大。

TA貢獻1802條經(jīng)驗 獲得超6個贊
Button newButton = new Button(null);
你給上下文空,我建議你給適當(dāng)?shù)纳舷挛?。您也可以為按鈕設(shè)置標(biāo)簽newButton.setTag(value)

TA貢獻1794條經(jīng)驗 獲得超7個贊
您的代碼不正確,您創(chuàng)建一個按鈕并添加到 LinearLayout,然后調(diào)用 startActivity 以加載 Activity。所以你重置了 LinearLayout 并清除了按鈕。
你應(yīng)該 :
run = (Button)findViewById(R.id.btnRunChallengeMode);
run.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent newForm = new Intent(Form2.this,Form2.class);
newForm.putExtra("a", a);
startActivity(newForm);
}
});
并在 create 中,獲取 Extras :
String a = getIntent().getIntExtra("a");
現(xiàn)在您可以創(chuàng)建按鈕了。
添加回答
舉報