getColorStateList已被弃用

fkc*_*aud 23 android android-theme

我在这里遇到了问题.我刚刚从sdk 22更新到23,并且不推荐使用以前版本的"getColorStateList()".

我的代码是这样的

seekBar.setProgressTintList(getResources().getColorStateList(R.color.bar_green));
valorslide.setTextColor(getResources().getColorStateList(R.color.text_green));
Run Code Online (Sandbox Code Playgroud)

较旧的"getColorStateList"是

getColorStateList(int id)
Run Code Online (Sandbox Code Playgroud)

新的是

getColorStateList(int id, Resources.Theme theme)
Run Code Online (Sandbox Code Playgroud)

我如何使用Theme变量?提前致谢

use*_*603 44

虽然anthonycr的答案有效,但只是写作更紧凑

ContextCompat.getColorStateList(context, R.color.haml_indigo_blue);
Run Code Online (Sandbox Code Playgroud)


ant*_*ycr 29

Theme对象是用于设置颜色状态列表样式的主题.如果您没有使用任何特殊主题与个人资源,您可以传递null或当前主题如下:

TextView valorslide; // initialize
SeekBar seekBar; // initialize
Context context = this;
Resources resources = context.getResources();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    seekBar.setProgressTintList(resources.getColorStateList(R.color.bar_green, context.getTheme()));
    valorslide.setTextColor(resources.getColorStateList(R.color.text_green, context.getTheme()));
} else {
    seekBar.setProgressTintList(resources.getColorStateList(R.color.bar_green));
    valorslide.setTextColor(resources.getColorStateList(R.color.text_green));
}
Run Code Online (Sandbox Code Playgroud)

如果你不关心主题,你可以传递null:

getColorStateList(R.color.text_green, null)
Run Code Online (Sandbox Code Playgroud)

有关更多说明,请参阅文档.注意,您只需要在API 23(Android Marshmallow)及更高版本上使用新版本.

  • 或者,只要坚持使用已弃用的版本,除非你的`minSdkVersion`为23或更高版本,否则无论如何都需要在旧设备上使用已弃用的版本. (2认同)