动态改变Android中按钮的宽度
我的问题很简单,我正在尝试动态更改此按钮的宽度:
<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>
这是我使用的代码:
Button myButton = (Button) findViewById(R.id.II3);
myButton.setWidth(10);
myButton.setText("kl");
文本确实改变了,但宽度没有改变。听起来好像有一个错误。 它的右侧还有另一个按钮,当该按钮减小到 10 像素时,它应该填补空白,所以我也无法更改上面的 LinearLayout。
任何解释&解决方案 ?应该可以用吧?谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为在您的具体情况下,wrap_content 不适用于您,对吧?
如果您需要绝对宽度,那么您需要通过新的 LayoutParameters 进行分配,即
someDensityFactor 是您的屏幕密度(浮动)。您可能还需要使布局无效才能重新绘制按钮。
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.
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.
建议尝试在父视图上调用 invalidate() (这将导致对所有子视图进行绘图调用 - 包括您的按钮)。这可能不起作用,因为您还需要按钮重新运行其 onMeasure() 逻辑(在绘制之前运行)。
使用使父级调用子级的 onMeasure 的无效方法或任何其他方法。
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.