2

我在矩形切换按钮中显示了以下可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">

            <solid android:color="@color/cerulean_blue"/>
            <stroke android:color="@android:color/transparent"/>

            <corners
                android:radius="@dimen/number_selection_rounding_radius"/>
        </shape>
    </item>
    <item android:left="10dp" android:right="10dp" android:top="5dp" android:bottom="5dp">
        <shape android:shape="oval">

            <solid android:color="@color/light_background"/>
            <stroke android:color="@android:color/transparent"/>

        </shape>
    </item>
</layer-list>

这会产生一个椭圆作为内部形状。不管视图的形状如何,我都想把它做成一个圆圈。我尝试为形状中的 size 元素指定各种值。我知道这应该会影响缩放,但无论使用的值如何,它都绝对没有影响。

在这种情况下是否有可能保持一个完美的圆圈,还是我需要以编程方式执行此操作?

4

1 回答 1

0

我放弃了矩形切换按钮,并强迫它们与这个类保持一致:

    public class SquareToggleButton extends ToggleButton {
    public SquareToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SquareToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareToggleButton(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int desiredSize = Math.max(widthSize,heightSize);

        int width;
        int height;

        // Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            // Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            // Can't be bigger than...
            width = Math.min(desiredSize, widthSize);
        } else {
            // Be whatever you want
            width = desiredSize;
        }

        // Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            // Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            // Can't be bigger than...
            height = Math.min(desiredSize, heightSize);
        } else {
            // Be whatever you want
            height = desiredSize;
        }

        int side = Math.max(width,height);

        setMeasuredDimension(side, side);
    }
}
于 2017-01-18T04:35:48.487 回答