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.

4

2 回答 2

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);
于 2012-12-19T10:56:54.593 回答
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);
于 2012-12-19T10:24:05.777 回答