创建一个不完整的按钮笔划

时间:2013-07-18 03:01:22

标签: android android-xml android-button android-resources android-drawable

目标:仅限上下。

我尝试了什么:

下面是我的XML副本。 我试过在This Stack Overflow Answer中关注解决方案。 但我的问题是,根据解决方案,不允许我选择按左右切断1dp的选项。

有什么想法吗?

代码:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape >
            <gradient
                    android:startColor="@color/secondaryButtonStartColorSelected"
                    android:endColor="@color/secondaryButtonEndColorSelected"
                    android:angle="270" />
            <stroke
                    android:width="@dimen/secondary_button_border_size"
                    android:color="@color/secondaryButtonBorderColorSelected" />

        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                    android:startColor="@color/secondaryButtonStartColorSelected"
                    android:endColor="@color/secondaryButtonEndColorSelected"
                    android:angle="270" />
            <stroke
                    android:width="@dimen/secondary_button_border_size"
                    android:color="@color/secondaryButtonBorderColorSelected"/>

        </shape>
    </item>

</selector>

1 个答案:

答案 0 :(得分:0)

您可以创建自定义Drawable来为您处理此问题,但您必须在代码与XML中进行设置。这是一个快速而肮脏的版本:

public class HorizontalStrokeDrawable extends Drawable {
    private Paint mPaint = new Paint();
    private int mStrokeWidth;

    public HorizontalStrokeDrawable (int strokeColor, int strokeWidth) {
        mPaint.setColor(strokeColor);
        mStrokeWidth = strokeWidth;
    }

    @Override
    public void draw (Canvas canvas) {
        Rect bounds = getBounds();
        canvas.drawRect(0, 0, bounds.right, mStrokeWidth, mPaint);
        canvas.drawRect(0, bounds.bottom - mStrokeWidth, bounds.right, bounds.bottom, mPaint);
    }

    @Override
    public void setAlpha (int alpha) {
        mPaint.setAlpha(alpha);
        invalidateSelf();
    }

    @Override
    public void setColorFilter (ColorFilter cf) {
        mPaint.setColorFilter(cf);
        invalidateSelf();
    }

    @Override
    public int getOpacity () {
        return PixelFormat.TRANSLUCENT;
    }
}

现在您可以在任何需要的地方设置它:

view.setBackgroundDrawable(new HorizontalStrokeDrawable(myColor, myStrokeWidth));