Reputation: 537
I am trying to change the height and width of a button through code at runtime.
My layout xml
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:layout_below="@+id/button2"
android:background="@drawable/button1_background"
/>
Main activity code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//some other code
int displaywidth= getResources().getDisplayMetrics().widthPixels;
Button f_button = (Button) findViewById(R.id.button1);
Log.d("F_button width before is",""+ f_button.getWidth());
f_button.setWidth(displaywidth/2);
Log.d("F_button width after is",""+ f_button.getWidth());
//some other code
}
The Logcat shows both F_button after and before width as "0".
what am I doing wrong.
thanks!.
Upvotes: 3
Views: 11852
Reputation: 940
Yes, I tried to solve the problem for a long time. Ajay's solution made me successful. For Kotlin programmers it looks like this:
btn.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 60)
Upvotes: 0
Reputation: 1189
i think it might help you..
Button btn = (Button)findViewById(R.id.btn1);
android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,60); // 60 is height you can set it as u need
btn.setLayoutParams(lp);
Upvotes: 3
Reputation: 1703
you should use
int displaywidth= getResources().getDisplayMetrics().widthPixels;
ViewGroup.LayoutParams buttonlp= (ViewGroup.LayoutParams)f_button.getLayoutParams();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(displaywidth, buttonlp.height);
buttonlp.setLayoutParams(params);
Instead of LinearLayout
you should use the parent layout of the button if it is not LinearLayout
Upvotes: 0