Code example for ColorStateList

Methods: getColorForState, isStateful

0
    } 
 
    @Override 
    protected void drawableStateChanged() { 
        super.drawableStateChanged(); 
        if (mTextColor != null && mTextColor.isStateful()) {
            updateTextColors(); 
        } 
    } 
 
    /** 
     * Sets the text to display in this widget. 
     * 
     * @param text 
     *            The text to display. 
     */ 
    public void setText(CharSequence text) {
        mText = text;
        requestLayout();
        invalidate();
    } 
 
    /** 
     * Sets the text size for this widget. 
     * 
     * @param size 
     *            Font size. 
     */ 
    public void setTextSize(int size) {
        setRawTextSize(size);
    } 
 
    /** 
     * Set the default text size to a given unit and value. See {@link TypedValue} for the possible dimension units. 
     * 
     * @param unit 
     *            The desired dimension unit. 
     * @param size 
     *            The desired size in the given units. 
     */ 
    public void setTextSize(int unit, float size) {
        Context c = getContext();
        Resources r;
 
        if (c == null)
            r = Resources.getSystem();
        else 
            r = c.getResources();
 
        setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()));
    } 
 
    private void setRawTextSize(float size) {
        if (size != mTextPaint.getTextSize()) {
            mTextPaint.setTextSize(size);
 
            requestLayout();
            invalidate();
        } 
    } 
 
    /** 
     * Sets the text color for all the states (normal, selected, 
     * focused) to be this color. 
     */ 
    public void setTextColor(int color) {
        mTextColor = ColorStateList.valueOf(color);
        updateTextColors(); 
    } 
 
    /** 
     * Sets the text color. 
     */ 
    public void setTextColor(ColorStateList colors) {
        final ColorStateList defList = Resources.getSystem().getColorStateList(android.R.color.primary_text_dark);
        mTextColor = colors != null ? colors : defList;
        updateTextColors(); 
    } 
 
    private void updateTextColors() { 
        boolean inval = false;
        int color = mTextColor.getColorForState(getDrawableState(), 0);
        if (color != mCurTextColor) {
            mCurTextColor = color;
            inval = true;
        } 
        if (inval) {