2017-07-30 35 views
-2

我想要使用getresources.getColor(resource id)获取颜色元素,但是android会告诉我它已被弃用使用getresources.getColor(resource id, theme)如何使用新版本的getresources()。getColor?

如何告诉它使用什么主题?我曾尝试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 公共无效的onDraw(帆布帆布){ 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(); 
    

    } }

任何帮助不胜感激。

回答

1

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

+0

是的。这是处理支持不同API的推荐方式。 – Gary99

+0

使用null作为主题清除错误,但应用程序无法启动。 – user182162

+0

我试过使用ContextCompat,但我不断收到版本错误的sdk – user182162

0

感谢您的所有输入。 ContextCompat.getColor就像修复错误一样工作。接口,枚举错误是由于多余的右括号。

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

相关问题