Android - 在 API 24 之前以编程方式将 TextView 背景设置为可绘制
Android - Set TextView background programatically to drawable before API 24
我正在尝试将充当按钮的 TextView 的背景设置为 XML 矢量。
if (condition) {
textViewButton.setBackgroundResource(R.drawable.button_selected);
} else if (condition) {
textViewButton.setBackgroundResource(R.drawable.button_correct);
} else {
textViewButton.setBackgroundResource(R.drawable.button_unselected);
}
我认为这是在 API24 中引入的,我无法在我的 API22 测试 phone 中加载它,因为我收到以下错误:
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f070069
at android.content.res.Resources.getValue(Resources.java:1324)
at android.content.res.Resources.getDrawable(Resources.java:828)
at android.content.Context.getDrawable(Context.java:408)
at android.view.View.setBackgroundResource(View.java:16251)
at androidx.appcompat.widget.AppCompatTextView.setBackgroundResource(AppCompatTextView.java:113)<
是否有任何方法可以通过编程方式为较旧的 API 完成对 imageView 设计的更改?(在 API 29 和 30 上工作得很好)
这是推荐的方式
textViewButton.setBackground(ContextCompat.getDrawable(context,R.drawable.button_selected));
如果它在您应用的 build.gradle
中不起作用,您需要包括:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
并将以下内容添加到 onCreate
:
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
我正在尝试将充当按钮的 TextView 的背景设置为 XML 矢量。
if (condition) {
textViewButton.setBackgroundResource(R.drawable.button_selected);
} else if (condition) {
textViewButton.setBackgroundResource(R.drawable.button_correct);
} else {
textViewButton.setBackgroundResource(R.drawable.button_unselected);
}
我认为这是在 API24 中引入的,我无法在我的 API22 测试 phone 中加载它,因为我收到以下错误:
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f070069
at android.content.res.Resources.getValue(Resources.java:1324)
at android.content.res.Resources.getDrawable(Resources.java:828)
at android.content.Context.getDrawable(Context.java:408)
at android.view.View.setBackgroundResource(View.java:16251)
at androidx.appcompat.widget.AppCompatTextView.setBackgroundResource(AppCompatTextView.java:113)<
是否有任何方法可以通过编程方式为较旧的 API 完成对 imageView 设计的更改?(在 API 29 和 30 上工作得很好)
这是推荐的方式
textViewButton.setBackground(ContextCompat.getDrawable(context,R.drawable.button_selected));
如果它在您应用的 build.gradle
中不起作用,您需要包括:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
并将以下内容添加到 onCreate
:
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);