如何在安卓中动态创建按钮?

Links

我想创建一个这样的页面。这7个按钮已经存在,但如果用户想添加更多类别(按钮),那么他可以使用+按钮和删除使用-按钮。任何想法或教程来制作这个?


答案 1

创建/删除按钮,如下所示:onClick+ button- button

  public void onClick(View v) {

     switch(v.getId()){
     case (R.id.plusbutton):
                 Button myButton = new Button(this);
                 myButton.setText("Add Me");

                 LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
                 LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                 ll.addView(myButton, lp);
                 break;.
     case (R.id.minusbutton):
                 Button myButton = new Button(this);
                 myButton.setText("Remove Me");

                 LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
                 LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                 ll.removeView(myButton, lp);
                 break;
           }
         }

答案 2

这是为了在安卓中动态创建按钮

LinearLayout row2 = (LinearLayout) findViewById(R.id.hll2);
Button ivBowl = new Button(this);
ivBowl.setText("hi");
LinearLayout.LayoutParams layoutParams = new  LinearLayout.LayoutParams(70, 70);
layoutParams.setMargins(5, 3, 0, 0); // left, top, right, bottom
ivBowl.setLayoutParams(layoutParams);
row2.addView(ivBowl);

推荐