动态改变Android中按钮的宽度

发布于 2024-11-01 16:47:23 字数 582 浏览 1 评论 0原文

我的问题很简单,我正在尝试动态更改此按钮的宽度:

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒浓于脸红 2024-11-08 16:47:23

我认为在您的具体情况下,wrap_content 不适用于您,对吧?
如果您需要绝对宽度,那么您需要通过新的 LayoutParameters 进行分配,即

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

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.

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.

静若繁花 2024-11-08 16:47:23

建议尝试在父视图上调用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文