2015-05-09 43 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); 

    } 

    ... 

} 

谢谢你的关心。

相关问题