0

目的:只描繪頂部和底部。創建一個不完整的按鈕描邊

我已經試過:

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

回答

0

你可以創建一個自定義Drawable來處理這個給你,但你必須將其設置在代碼VS 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));