【问题标题】:Create an Incomplete Button Stroke创建不完整的按钮描边
【发布时间】:2013-07-16 19:59:38
【问题描述】:

目标:只画顶部和底部。

我的尝试:

下面是我的 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>

【问题讨论】:

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


    【解决方案1】:

    您可以创建一个自定义 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多