开发者

Android: generic way to set Widget's dimensions in code?

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 widge开发者_开发技巧t dimensions in code?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜