动态添加按钮并删除创建的最后一个按钮

时间:2016-11-12 17:37:06

标签: android android-layout android-button

我创建了一个Add按钮,它将动态添加New按钮。我还想在删除按钮时删除最后创建的按钮。我怎么能这样做?

public class Stack extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stack);
    final LinearLayout dynamicButtonsLinearLayout = (LinearLayout) findViewById(R.id.dynalayout);

    final int iNumberOfButtons =  1;
    final Button[] dynamicButtons = new Button[iNumberOfButtons];

    final LinearLayout.LayoutParams paramsButton = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    paramsButton.gravity= Gravity.CENTER;
    Button addButton = (Button) findViewById(R.id.button);
    final Button removeButton = (Button) findViewById(R.id.button2);
    addButton.setOnClickListener(new View.OnClickListener() {
        int num=0; //ID INCREMENT
        public void onClick(View v) {

            for (int i = 0; i < iNumberOfButtons; i++) {
                dynamicButtons[i] = new Button(Stack.this);
                dynamicButtons[i].setText(String.valueOf(num));
                dynamicButtons[i].setId(num);
                dynamicButtons[i].setTextSize(15.0f);
                dynamicButtons[i].setLayoutParams(paramsButton);
                dynamicButtonsLinearLayout.addView(dynamicButtons[i]);
                removeButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //I WANT REMOVE THE VIEW IN THE LAST BUTTON

                    }
                });
            }
            num=num+1;
        }
    });


       ; // dynamicButtonsLinearLayout is the container of the buttons

  }
}

这是我的XML设计,它显示了我动态创建的按钮

enter image description here

1 个答案:

答案 0 :(得分:0)

以下是我在代码中更改的内容,以便添加(如push)和删除(pop)。我猜是堆栈可视化。

public function show_list() {
    $this->load->model('model_lists');
    $data = $this->model_lists->get_list_details();
    $this->load->view('lists/view_list', $data);
}