Search code examples
javaandroidtextview

Android - Set TextView background programatically to drawable before API 24


I am trying to set the background of an TextView that acts as a button to an XML vector.


    if (condition) {
       textViewButton.setBackgroundResource(R.drawable.button_selected);
      } else if (condition) {
       textViewButton.setBackgroundResource(R.drawable.button_correct);
      } else {
        textViewButton.setBackgroundResource(R.drawable.button_unselected);
      } 

I thing this was introduced in API24 and I can't load it in my API22 test phone as I get the following error:

   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)<

Is there any way to acomplish this changes to imageView design programaticaly for older API's?(works just fine on API 29 and 30)


Solution

  • This is the recommended way

    textViewButton.setBackground(ContextCompat.getDrawable(context,R.drawable.button_selected));

    If it doesn't work in your app's build.gradle you need to include:

    android {
        defaultConfig {
            vectorDrawables.useSupportLibrary = true
        }
    }
    

    And add the following to onCreate:

    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);