Simon
Simon

Reputation: 63

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

Upvotes: 6

Views: 5469

Answers (2)

BonanzaDriver
BonanzaDriver

Reputation: 6452

As a suggestion try calling invalidate() on the parent view (which will cause drawing invocations to all the children - including your button). This might not work because what you also need is for the button to re-run its onMeasure() logic (which runs prior to drawing).

Play with either invalidating or any other method which will cause the parent to invoke the onMeasure of the children.

Upvotes: 0

Mathias Conradt
Mathias Conradt

Reputation: 28705

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.

Upvotes: 2

Related Questions