开发者

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="@dr开发者_StackOverflowawable/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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜