Rasoul Miri
Rasoul Miri

Reputation: 12222

AppCompatImageView set background android 17

I have vector icon and use AppCompatImageView in XML

layout.xml

<android.support.v7.widget.AppCompatImageView
            android:layout_width="16dp"
            android:layout_height="16dp"
            android:background="@drawable/ic_location"/>

ic_location.xml

<?xml version="1.0" encoding="UTF-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="28dp"
    android:viewportHeight="28"
    android:viewportWidth="25">
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M12.5107,11.0107m3.3369,0a3.3369,3.3369 0,1 0,-6.6738 0a3.3369,3.3369 0,1 0,6.6738 0"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
    <path
        android:fillColor="#00000000"
        android:fillType="evenOdd"
        android:pathData="M2.5,11.0107C2.5,16.5391 12.5107,26.861 12.5107,26.861C12.5107,26.861 22.5214,16.5391 22.5214,11.0107C22.5214,5.4819 18.0394,1 12.5107,1C6.9819,1 2.5,5.4819 2.5,11.0107Z"
        android:strokeColor="@color/mediumGray"
        android:strokeLineCap="square"
        android:strokeWidth="2" />
</vector>

Log error

E/AndroidRuntime: FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #61: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)

it works on API 21 and above but not work on 17 API device.

when using app:srcCompat work but when use android:background app crash.

Upvotes: 0

Views: 647

Answers (1)

yaromchikV
yaromchikV

Reputation: 99

You should add AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) to your activity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    setContentView(R.layout.activity_main)
}

After that, you can set the background programmatically. For example: image.setBackgroundResource(R.drawable.ic_circle)

Upvotes: 2

Related Questions