2014-09-12 47 views
3

我有一個XML文件中定義的背景的EditText如何從GradientDrawable獲取顏色?

<EditText 
    android:id="@+id/myEditText" 
    style="@style/Theme.x.EditText.ReadOnly" 
    android:layout_marginRight="5dip" 
    android:layout_span="7" 
    android:nextFocusDown="@+id/myEditText2" 
    android:selectAllOnFocus="true" /> 

xml文件:my_edit_text.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <gradient android:startColor="@android:color/background_dark" android:endColor="@android:color/background_dark" 
     android:angle="0"/> 
    <solid android:color="#FA0000"/> 
    <stroke android:width="1px" android:color="#5A5D5A"/> 
    <corners 
     android:bottomLeftRadius="3dip" 
     android:topLeftRadius="3dip" 
     android:bottomRightRadius="3dip" 
     android:topRightRadius="3dip" 
     android:color="@color/crAmarelo"/> 
    <padding 
     android:left="5dip" 
     android:right="5dip"/> 
</shape> 

,我需要得到該視圖有顏色:

EditText et = (EditText) solo.getView(R.id.myEditText); 
GradientDrawable gd = (GradientDrawable) et.getBackground(); 

但我不知道如何從GradientDrawable獲得純色。

+0

漸變是顏色之間的插值 - 不是一個單一的顏色。除非您指定視圖的特定像素,否則嘗試獲取View的整體顏色(如果它是漸變的)是沒有意義的。如果您正在談論「純色」,那不是'GradientDrawable',而是''Shape''標籤定義的'ShapeDrawable'的一個屬性。 – kcoppock 2014-09-12 21:40:02

+0

@ kcoppock是的,我正在談論'固體'顏色。當我嘗試這個:'EditText et =(EditText)solo.getView(R.id.myEditText); ShapeDrawable sd =(ShapeDrawable)et.getBackground();'我有一個錯誤'java.lang.ClassCastException:android.graphics.drawable.GradientDrawable不能轉換爲android.graphics.drawable.ShapeDrawable' – Daniane 2014-09-15 12:52:12

回答

2

您可以參考GradientDrawable.java然後做一些適當的修改,以使其工作〜

import android.content.res.Resources; 
... 

// it's the same with the GradientDrawable, just make some proper modification to make it compilable 
public class ColorGradientDrawable extends Drawable { 
    ... 
    private int mColor; // this is the color which you try to get 
    ... 
    // original setColor function with little modification 
    public void setColor(int argb) { 
     mColor = argb; 
     mGradientState.setSolidColor(argb); 
     mFillPaint.setColor(argb); 
     invalidateSelf(); 
    } 

    // that's how I get the color from this drawable class 
    public int getColor() { 
     return mColor; 
    } 
    ... 

    // it's the same with GradientState, just make some proper modification to make it compilable 
    final public static class GradientState extends ConstantState { 
     ... 
    } 
} 
+0

請幫助我們如何才能參考ColorGradientDrawable, – 2014-10-27 06:21:07

+1

你複製GradientDrawable.java,然後你改變它的類名稱,添加一些像「mColor」這樣的變量,並做了上面提到的適當修改,然後它就起作用了〜 – shanwu 2014-10-27 13:23:17

+0

我們在XML中放入了什麼,以便它可以引用ColorGradientDrawable? – 2014-10-28 00:10:40