1
我想要動態創建和刪除按鈕,並在下面的代碼中建立,其中第一次刪除做得很好,當通過按添加創建新按鈕 按鈕,然後我想刪除我的按鈕,但它只刪除沒有按鈕空間的按鈕ID,並且此ID可以用於第二次;請幫我理解這個問題。動態創建和刪除按鈕。第一次刪除做得很好,但第二次只能從佈局刪除沒有按鈕空間的ID
代碼:
public class MainActivity extends ActionBarActivity {
Button Add;
Button Remove;
public int Bindex=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.Add);
Remove= (Button) findViewById(R.id.Remove);
Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bindex++;
final LinearLayout layout = (LinearLayout) findViewById(R.id.ButtonLinearLayout);
final Button Btn = new Button(MainActivity.this);
Btn.setId(Bindex);
Btn.setBackgroundColor(2);
Btn.setTextSize(12);
Btn.setWidth(5);
layout.addView(Btn);
Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout.setBackgroundColor(bn.getSolidColor());
Btn.setText(String.valueOf(Btn.getId()));
}
});
}
Remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button rmButton=(Button)findViewById(Bindex);
rmButton.setVisibility(View.GONE);
Bindex--;
}
}