Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the width of a button in Android

My question is very simple, I'm trying to dynamically change the width of this button :

<Button> 
    android:layout_height="35dip" 
    android:background="@drawable/buttonlesson" 
    android:text="Level 3 [TAP HERE]" 
    android:onClick="MenuLI1L3" 
    android:layout_width="300dp" 
    android:id="@+id/II3"
</Button>

Here is the code I use :

 Button myButton = (Button) findViewById(R.id.II3);
 myButton.setWidth(10);
 myButton.setText("kl");

Text indeed change but not the width. Sound like there is a bug. There is another button on its right which suppose to fill the gap when this button is reduced to 10 pixel, so I can't change the LinearLayout above too.

Any explanation & solution ? It should work no? Thanks

like image 377
Simon Avatar asked Apr 17 '11 04:04

Simon


1 Answers

I assume wrap_content doesn't work for your in your specific case, right? If you need absolute width, then you need to assign that via new LayoutParameters, i.e.

myButton.setLayoutParams(new LinearLayout.LayoutParams(
    30 * someDensityFactor, LinearLayout.LayoutParams.WRAP_CONTENT
))

where the someDensityFactor is your screen density (float). You also might need to invalidate your layout then as well in order to get the button repainted.

like image 86
Mathias Conradt Avatar answered Oct 30 '22 03:10

Mathias Conradt