Android:在代码中设置小部件尺寸的通用方法?

发布于 2024-12-08 12:52:06 字数 672 浏览 1 评论 0原文

我有一个自定义按钮,我想在代码中设置其尺寸(而不是在 xml 中),以便用户可以自定义尺寸。看似显而易见的方法是:

public class MyButton extends Button
{
    public MyButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        int buttonSize = getSize();
        setLayoutParams(new LinearLayout.LayoutParams(buttonSize, buttonSize));
    }

但是,这并不通用,因为它仅在 Button 的父级是 LinearLayout 时才有效。相反,我尝试了这个:

@Override
protected void onMeasure(int specw, int spech)
{
    int spec = MeasureSpec.makeMeasureSpec(getButtonSize()), MeasureSpec.EXACTLY);
    super.onMeasure(spec, spec);
}

......这似乎运作良好。有人知道这有什么缺点吗?或者知道在代码中通用设置小部件尺寸的更好方法?

I have a custom Button and I want to set its dimensions in code (as opposed to in xml), so that users can customize the dimensions. The seemingly obvious way to this is:

public class MyButton extends Button
{
    public MyButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        int buttonSize = getSize();
        setLayoutParams(new LinearLayout.LayoutParams(buttonSize, buttonSize));
    }

However, this fails to be generic because it only works if the Button's parent is a LinearLayout. Instead, I tried this:

@Override
protected void onMeasure(int specw, int spech)
{
    int spec = MeasureSpec.makeMeasureSpec(getButtonSize()), MeasureSpec.EXACTLY);
    super.onMeasure(spec, spec);
}

...which seems to work well. Is anyone aware of any shortcomings to this? or aware of a better way to generically set widget dimensions in code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

站稳脚跟 2024-12-15 12:52:06

从 onMeasure() 执行此操作是一个很好的方法(即使您的代码不起作用,因为您没有使用您创建的度量规范。)您还可以覆盖 onFinishInflate() 并调用 getLayoutParams() 和更改宽度和高度字段。

Doing it from onMeasure() is a good way to do it (even though your code doesn't work since you're not using the measure spec you've created.) You could also override onFinishInflate() and call getLayoutParams() and change the width and height fields.

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