如何使用新版本的getresources()。getColor?

时间:2017-07-30 15:59:54

标签: android android-theme android-color

我正在尝试使用getresources.getColor(resource id)获取一个颜色元素,但是android告诉我它已被弃用getresources.getColor(resource id, theme)

如何判断使用什么主题?我试过R.style.AppTheme但是我得到一个错误,因为这是一个int值

public class TodoListItemView extends AppCompatTextView {
    public TodoListItemView(Context context, AttributeSet attributeSet, int ds) {
        super(context, attributeSet, ds);
        init();
    }

    public TodoListItemView(Context context) {
        super(context);
        init();
    }

    public TodoListItemView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

    private Paint marginPaint;
    private Paint linePaint;
    private int paperColor;
    private float margin;

    private void init() {
        Resources myResources = getResources();
        marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        marginPaint.setColor(getResources().getColor(R.color.notepad_margin));
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setColor(myResources.getColor(R.color.notepad_lines));
        paperColor = myResources.getColor(R.color.notepad_paper);
        margin = myResources.getDimension(R.dimen.notepad_margin);
    }

    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawColor(paperColor);
        canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);
        canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight(), linePaint);

        canvas.drawLine(margin, 0, margin, getMeasuredHeight(), marginPaint);

        canvas.save();
        canvas.translate(margin, 0);

        super.onDraw(canvas);
        canvas.restore();
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

使用ContextCompat.getColor(context, R.color.your_color);

答案 1 :(得分:0)

感谢所有输入。 ContextCompat.getColor可以修复错误。接口,枚举错误是由于一个无关的结束括号。

我唯一的抱怨是现在该应用程序无法运行。模拟器上会显示一条消息,指出应用程序已停止工作。没有机会测试变化。

相关问题