如何在android中动态创建Button?

Smi*_*ian 15 java android android-intent android-layout android-button

链接

我想创建一个这样的页面.这7个按钮已经存在但是如果用户想要添加更多类别(按钮),那么他可以使用+按钮并使用-按钮删除.这个有什么想法或教程吗?

Ava*_*i Y 23

创建/删除按钮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;
           }
         }
Run Code Online (Sandbox Code Playgroud)

  • 什么是buttonlayout?如何创造 (5认同)

Roh*_*hit 10

这是在android中动态创建按钮

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);
Run Code Online (Sandbox Code Playgroud)