0

Possible Duplicate:
how to add button dynamically in android?

I need to create a button in android without using xml.I have tried the following code:

Button b=new Button(this);
b.setWidth(50);

However, It isn't displaing in runtime.

Community
  • 1
  • 1
Selva
  • 59
  • 4

2 Answers2

1
 Button myButton = new Button(this);
    myButton.setText("Push Me");
    myButton.height = 60;
    myButton.width = 60;
    LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
    LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    ll.addView(myButton, lp);
Nipun Gogia
  • 1,846
  • 1
  • 11
  • 17
0

You need to add the view to the layout before it will be shown on the screen.

Button b=new Button(this);
b.setWidth(50);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);

layout.addView(b);
Aelexe
  • 1,216
  • 3
  • 18
  • 27