2013-07-17 2 views
17

У меня есть пользовательский вид, в котором я хочу установить цвет текстового поля.Пользовательский attr get color возвращает недопустимые значения

У меня есть

attrs.xml

<declare-styleable name="PropertyView"> 
    <attr name="propertyTitle" format="string" localization="suggested" /> 
    <attr name="showTitle" format="boolean" /> 
    <attr name="propertyTextColor" format="color" /> 
    <attr name="propertyTextSize" format="dimension" /> 
</declare-styleable> 

я поставил его в файл макета

<com.something.views.PropertyView 
    android:id="@+id/dwf_rAwayTeamTimePenaltyInput" 
    style="@style/mw" 
    propertyview:propertyTextSize="16sp" 
    propertyview:propertyTitle="@string/AwayTeam" 
    propertyview:showTitle="true" 
    propertyview:propertyTextColor="@color/textLight" /> 

И в моем коде я поставил его

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PropertyView, 0, 0); 

    showTitle = a.getBoolean(R.styleable.PropertyView_showTitle, false); 
    String title = a.getString(R.styleable.PropertyView_propertyTitle); 
    float textSize = a.getDimension(R.styleable.PropertyView_propertyTextSize, -1); 
    int color = a.getColor(R.styleable.PropertyView_propertyTextColor, -1); 
    textSize = textSize/getResources().getDisplayMetrics().scaledDensity; 
    if(BuildConfig.DEBUG) Log.e(getClass().getName(), "Color set to: " + color); 

    setShowTitle(showTitle); 
    setTitle(title); 
    if(textSize >= 0) mTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); 
    if(color != -1) mTitleTextView.setTextColor(color); 

    a.recycle(); 

Но цвет продолжает возвращать -1. Я также попытался установить цвет # 000 Когда я делаю что я получаю значение -16777216

Я также попытался a.getInteger и a.getInt

опыт Любой человек с этой проблемой или предложения?

решение, благодаря Alex Fu

GetColor не может обрабатывать ссылки

В настоящее время она работает с

ColorStateList color = a.getColorStateList(R.styleable.PropertyView_propertyTextColor); 
mTitleTextView.setTextColor(color); 

ответ

16

Вы используете ссылки на цвет в вашем примере, однако, по к вашему файлу attrs.xml, это свойство должно иметь тип цвета, а не ссылку. Вероятно, это причина, по которой вы использовали шестнадцатеричный код цвета, но с использованием ссылки, возвращенной -1.

Если вы изменили формат на ссылку, вы также должны изменить способ, чтобы получить его от a.getColor() до a.getColorStateList().

+0

Хорошая мысль, но слишком плохо это не решило. –

+0

Вы изменили формат ссылки на attrs.xml? Если да, изменили ли вы также метод 'a.getColor()'? Вместо этого вы должны попробовать использовать 'a.getColorStateList()'. 'getColorStateList' может понимать как сплошные цвета, так и ссылки. –

+0

Спасибо, что было =) глупо, что getColor не может обрабатывать ссылку, но, вероятно, имеет вескую причину. –

2

Это своего рода ошибка с attrs.

Следующие работы прекрасно.


attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <!-- Your View --> 
    <declare-styleable name="YourView"> 
     <attr name="tint_color" format="reference" /> <!-- Important --> 
     <attr name="ripple_drawable" format="reference" /> <!-- Important --> 
    </declare-styleable> 

</resources> 

YourView.java

public YourView(Context context) { 
    this(context, null); 
} 

public YourView(Context context, @Nullable AttributeSet attrs) { 
    this(context, attrs, 0); 
} 

public YourView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 

    // Get attrs 
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.YourView, defStyleAttr, 0); 

    // Set tint 
    int tintStyle = R.styleable.YourView_tint_color; 
    if (a.hasValue(tintStyle)) { 
     mTintColor = a.getResourceId(tintStyle, 0); // Important 
     setTint(mTintColor); 
    } 

    // Set Ripple 
    int rippleStyle = R.styleable.YourView_ripple_drawable; 
    if (a.hasValue(rippleStyle)) { 
     mRippleDrawable = a.getResourceId(rippleStyle, 0); // Important 
     setRipple(mRippleDrawable); 
    } 

    // End 
    a.recycle(); 
} 

Использование

<com.your.app.YourView 
    ... 
    app:ripple_drawable="@drawable/ripple_default" 
    app:tint_color="@color/colorWhite" /> 
Смежные вопросы