Reputation: 2671
Can somebody tell me why my button width is not increasing .what am i doing wrong. I am trying to create button dynamically and set their width and height.
public class MainActivity extends Activity {
LinearLayout l;
LinearLayout linear;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l=(LinearLayout) findViewById(R.id.linear);
for(int i=0;i<10;i++)
{
linear=new LinearLayout(this);
LinearLayout.LayoutParams par=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
linear.setLayoutParams(par);
linear.setOrientation(LinearLayout.HORIZONTAL);
Button b=new Button(this);
b.setId(i+1);
b.setText("button:"+(i+1));
b.setWidth(800);// set the width of button
b.setHeight(30);// height of button
linear.addView(b);
l.addView(linear); // main layout in which i have to show button
}
}
}
here is the output : what i am getting enter image description here
Upvotes: 1
Views: 220
Reputation: 2771
Also in this case you dont need to add the buttons in linear
(LinearLayout) since you are adding them first to linear
, and then adding linear
to l
in the same loop. Each LinearLayout(linear) will only hold one button, and no need for that. Either add all the buttons to linear
and when the loops finish you add them to l
(just once) or dont create 'linear' and add them directly to l
What you can do it this to make it more simple:
for(int i=0;i<10;i++)
{
Button b=new Button(this);
b.setId(i+1);
b.setText("button:"+(i+1));
b.setWidth(800);// set the width of button
b.setHeight(30);// height of button
b.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
l.addView(b); // main layout in which i have to show button
}
Upvotes: 0
Reputation: 1268
Give the buttons layout width and height as you did for the LinearLayout.
Upvotes: 0
Reputation: 3972
To increase automatically your button width you can use wrap_content.
You can use this code to set LayoutParams programmatically
Put this:
b.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
before this:
linear.addView(b);
Upvotes: 1
Reputation: 3822
Add dynamic button with LayoutParams as below code,
Button b=new Button(this);
b.setId(i+1);
b.setText("button:"+(i+1));
LayoutParams lp1 = new LayoutParams(800,30);
linear.addView(b, lp1);
Upvotes: 0