2015-05-09 42 views
0

我有一個自定義View這樣的:如何在畫布後面設置自定義視圖的背景?

public class ShadowTextView extends TextView { 

... 

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

     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

     final int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 
     final int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 
     final int minSize = Math.min(parentWidth, parentHeight); 

     mShadow = new Paint(Paint.ANTI_ALIAS_FLAG); 

     RadialGradient gradient = new RadialGradient(
       parentWidth * mCenterX, 
       parentHeight * mCenterY, 
       minSize * mGradientRadiusWidthPercent, 
       new int[]{mStartColor, mCenterColor, mEndColor}, 
       null, 
       android.graphics.Shader.TileMode.CLAMP); 

     mShadow.setDither(true); 
     mShadow.setShader(gradient); 

    } 

    @Override 
    protected void onDraw(Canvas canvas) { 

     super.onDraw(canvas); 

     canvas.drawRect(0, 0, getWidth(), getHeight(), mShadow); 

    } 

... 

} 

在XML我想利用這個CustomView與背景,是在我的Canvas

<com.ShadowTextView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 

    android:background="@drawable/circle" 
    android:paddingBottom="3dp" 

    android:gravity="center" 
    android:text="+" 
    android:textColor="@android:color/white" 
    android:textSize="32dp" 

    app:startColor="@android:color/black" 
    app:centerColor="@android:color/black" 
    app:endColor="@android:color/transparent" 
    app:gradientRadiusWidthPercent=".5" 
/> 

的circle.xml:

<layer-list> 

    <item xmlns:android="http://schemas.android.com/apk/res/android" 
     android:bottom="6dp" 
     android:left="3dp" 
     android:right="3dp"> 

     <shape android:shape="oval"> 

      <!-- 
       accentColor might be material red #F44336 
      --> 

      <solid android:color="#F44336" /> 

     </shape> 

    </item> 

</layer-list> 

Canvas影子是在前臺,但應該是在後臺,這意味着android:background="@drawable/circly"和後面的文字。

目前的結果是:

wrong

所希望的結果:

correct

最後一個重要的注意事項:
我知道有很多開放的圖書館獲得的浮動行動按鈕。請不要轉介我。我想找到我自己的「解決方案」,以便設計一個textView。

+0

「android:background」是(如其名稱所示)放置在背景上,但您可以通過調用getBackground()來獲取背景Drawable – pskink

回答

3

解決方案非常簡單。 XML定義'android_background'的背景設置在draw(...)中繪製,而不是在onDraw(...)-方法中繪製。

所以,我所要做的就是在draw(...)方法中畫出我的影子,然後調用super.draw(...)方法繪製背景(在我的陰影上)。

此外,在super.draw(...)方法中,調用onDraw(...)方法來繪製TextView的文本。

相同的代碼與上面一點點的變化:

public class ShadowTextView extends TextView { 

    ... 

    // overriding of the draw() method instead of the onDraw(...) method 

    @Override 
    public void draw(Canvas canvas) { 

     canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mShadow); 

     /* 
      Draw the background setting by XML definition android:background 
     */ 
     super.draw(canvas); 

    } 

    ... 

} 

謝謝你的關心。

相關問題