Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Button Dynamically in android?

Links

I want to create a page like this. these 7 buttons are already exist but if user want to add more categories (button) then he can do using + button and delete using - button. Any idea or tutorial for making this?

like image 802
Smit Christian Avatar asked Feb 26 '13 06:02

Smit Christian


People also ask

How do you create a dynamic button?

This example demonstrates how do I add a button dynamically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

Create/Remove button onClick of + button and - button as below:

  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;
           }
         }
like image 140
Avadhani Y Avatar answered Sep 18 '22 20:09

Avadhani Y