programing tip

android : DrawableRight를 사용하여 버튼 및 TextViews에서 VectorDrawable을 사용할 수 있습니까?

itbloger 2020. 7. 22. 08:18
반응형

android : DrawableRight를 사용하여 버튼 및 TextViews에서 VectorDrawable을 사용할 수 있습니까?


textview 또는 imageview에서 VectorDrawable 자산을 사용하면 "android : DrawableRight"/ "android : DrawableEnd"/ "android : DrawableStart"/ "android : DrawableLeft"를 사용할 때 런타임 충돌이 발생합니다.

응용 프로그램은 경고없이 잘 컴파일됩니다.

나는 사용하고있다

  • 그레들 1.5
  • 지원 라이브러리 23.2 ( 'com.android.support:appcompat-v7:23.2.0')

내가 찾은 것은 프로그래밍 방식으로 Java에서 SVG를 이와 같은 충돌없이 할당 할 수 있다는 것입니다.

TextView tv = (TextView) findViewById(R.id.textView);
tv.setCompoundDrawablesWithIntrinsicBounds(null,null, getResources().getDrawable(R.drawable.ic_accessible_white_36px),null);

(23.2에 대한 지원 라이브러리 버그 인 것 같습니다.)

그러나 SVG 자산에 drawableRight 등을 사용할 수 있습니까?

여기 내 레이아웃이 있습니다

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="au.com.angryitguy.testsvg.MainActivity">


<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableRight="@drawable/ic_accessible_white_36px"
    android:background="@color/colorPrimary"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:text="Hello World!"/>
</RelativeLayout>

여기 내 활동이 있습니다

package au.com.angryitguy.testsvg;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        }
    }

다음은 Google 머티리얼 디자인 사이트의 수정되지 않은 VectorDrawable 자산입니다.

<vector android:height="24dp" android:viewportHeight="24.0"
    android:viewportWidth="24.0" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FFFFFF" android:pathData="M12,4m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
    <path android:fillColor="#FFFFFF" android:pathData="M19,13v-2c-1.54,0.02 -3.09,-0.75 -4.07,-1.83l-1.29,-1.43c-0.17,-0.19 -0.38,-0.34 -0.61,-0.45 -0.01,0 -0.01,-0.01 -0.02,-0.01L13,7.28c-0.35,-0.2 -0.75,-0.3 -1.19,-0.26C10.76,7.11 10,8.04 10,9.09L10,15c0,1.1 0.9,2 2,2h5v5h2v-5.5c0,-1.1 -0.9,-2 -2,-2h-3v-3.45c1.29,1.07 3.25,1.94 5,1.95zM12.83,18c-0.41,1.16 -1.52,2 -2.83,2 -1.66,0 -3,-1.34 -3,-3 0,-1.31 0.84,-2.41 2,-2.83L9,12.1c-2.28,0.46 -4,2.48 -4,4.9 0,2.76 2.24,5 5,5 2.42,0 4.44,-1.72 4.9,-4h-2.07z"/>
</vector>

여기 내 앱 build.gradle이 있습니다.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "au.com.angryitguy.testsvg"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        // Stops the Gradle plugin’s automatic rasterization of vectors
        generatedDensities = []
    }
    // Flag to tell aapt to keep the attribute ids around
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
}

여기 충돌이 있습니다. (텍스트 뷰를 참조하는 팽창 오류에 유의하십시오.)

03-02 07:56:08.808 13863-13863/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{au.com.angryitguy.testsvg/au.com.angryitguy.testsvg.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class TextView
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                at android.app.ActivityThread.access$600(ActivityThread.java:130)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                at android.os.Handler.dispatchMessage(Handler.java:99)
                at android.os.Looper.loop(Looper.java:137)
                at android.app.ActivityThread.main(ActivityThread.java:4745)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                at dalvik.system.NativeStart.main(Native Method)
                                                    Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class TextView
                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267)
                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
                at au.com.angryitguy.testsvg.MainActivity.onCreate(MainActivity.java:14)
                at android.app.Activity.performCreate(Activity.java:5008)
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
                at android.app.ActivityThread.access$600(ActivityThread.java:130) 
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
                at android.os.Handler.dispatchMessage(Handler.java:99) 
                at android.os.Looper.loop(Looper.java:137) 
                at android.app.ActivityThread.main(ActivityThread.java:4745) 
                at java.lang.reflect.Method.invokeNative(Native Method) 
                at java.lang.reflect.Method.invoke(Method.java:511) 
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
                at dalvik.system.NativeStart.main(Native Method) 
                                                    Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_accessible_white_36px.xml from drawable resource ID #0x7f02004b
                at android.content.res.Resources.loadDrawable(Resources.java:1918)
                at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
                at android.widget.TextView.<init>(TextView.java:622)
                at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:60)
                at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:56)
                at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
                at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:963)
                at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1022)
                at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675)
                at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267) 
                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129) 
                at au.com.angryitguy.testsvg.MainActivity.onCreate(MainActivity.java:14) 
                at android.app.Activity.performCreate(Activity.java:5008) 
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
                at android.app.ActivityThread.access$600(ActivityThread.java:130) 
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
                at android.os.Handler.dispatchMessage(Handler.java:99) 
                at android.os.Looper.loop(Looper.java:137) 
                at android.app.ActivityThread.main(ActivityThread.java:4745) 
                at java.lang.reflect.Method.invokeNative(Native Method) 
                at java.lang.reflect.Method.invoke(Method.java:511) 
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
                at dalvik.system.NativeStart.main(Native Method) 
                                                    Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #1: invalid drawable tag vector
                at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:877)
                at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818)
                at android.content.res.Resources.loadDrawable(Resources.java:1915)
                at android.content.res.TypedArray.getDrawable(TypedArray.java:601) 
                at android.widget.TextView.<init>(TextView.java:622) 
                at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:60) 
                at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:56) 
                at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103) 
                at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:963) 
                at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1022) 
                at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44) 
                at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:675) 
                at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
                at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267) 
                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129) 
                at au.com.angryitguy.testsvg.MainActivity.onCreate(MainActivity.java:14) 
                at android.app.Activity.performCreate(Activity.java:5008) 
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
                at android.app.ActivityThread.access$600(ActivityThread.java:130) 
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
                at android.os.Handler.dispatchMessage(Handler.java:99) 
                at android.os.Looper.loop(Looper.java:137) 
                at android.app.ActivityThread.main(ActivityThread.java:4745) 
                at java.lang.reflect.Method.invokeNative(Native Method) 
                at java.lang.reflect.Method.invoke(Method.java:511) 
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
                at dalvik.system.NativeStart.main(Native Method) 

SVG 자산에 drawableRight 등을 사용할 수 있습니까?

AppCompatTextView는 이제 지지체는 app:drawableLeftCompat, app:drawableTopCompat, app:drawableRightCompat, app:drawableBottomCompat, app:drawableStartCompatapp:drawableEndCompat화합물 드로어 블은 같은 그리기 유형 백 포트지지 VectorDrawableCompat.

이것을 gradle 파일에 포함하십시오

implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'

텍스트보기에서 사용할 수 있습니다

app:drawableLeftCompat
app:drawableStartCompat

기존 답변

Google은이 문제에 대해 곧 아무 일도하지 않을 것 같으므로 모든 앱에 대해보다 견고한 재사용 가능한 솔루션을 고안해야했습니다.

  1. 먼저 "res / values ​​/ attrs.xml" 의 attrs.xml 파일에 사용자 정의 TextView 속성을 추가 하십시오 .

    <resources>
        <declare-styleable name="CustomTextView">
            <attr name="drawableStartCompat" format="reference"/>
            <attr name="drawableEndCompat" format="reference"/>
            <attr name="drawableTopCompat" format="reference"/>
            <attr name="drawableBottomCompat" format="reference"/>
        </declare-styleable>
    </resources>
    
  2. 그런 다음 다음과 같이 사용자 정의 TextView 클래스를 작성하십시오.

    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.drawable.Drawable;
    import android.os.Build;
    import android.support.v7.content.res.AppCompatResources;
    import android.support.v7.widget.AppCompatTextView;
    import android.util.AttributeSet;
    
    public class CustomTextView extends AppCompatTextView {
        public CustomTextView(Context context) {
            super(context);
        }    
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initAttrs(context, attrs);
        }
        public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initAttrs(context, attrs);
        }
    
        void initAttrs(Context context, AttributeSet attrs) {
            if (attrs != null) {
                TypedArray attributeArray = context.obtainStyledAttributes(
                        attrs,
                        R.styleable.CustomTextView);
    
                Drawable drawableStart = null;
                Drawable drawableEnd = null;
                Drawable drawableBottom = null;
                Drawable drawableTop = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    drawableStart = attributeArray.getDrawable(R.styleable.CustomTextView_drawableStartCompat);
                    drawableEnd = attributeArray.getDrawable(R.styleable.CustomTextView_drawableEndCompat);
                    drawableBottom = attributeArray.getDrawable(R.styleable.CustomTextView_drawableBottomCompat);
                    drawableTop = attributeArray.getDrawable(R.styleable.CustomTextView_drawableTopCompat);
                } else {
                    final int drawableStartId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableStartCompat, -1);
                    final int drawableEndId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableEndCompat, -1);
                    final int drawableBottomId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableBottomCompat, -1);
                    final int drawableTopId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableTopCompat, -1);
    
                    if (drawableStartId != -1)
                        drawableStart = AppCompatResources.getDrawable(context, drawableStartId);
                    if (drawableEndId != -1)
                        drawableEnd = AppCompatResources.getDrawable(context, drawableEndId);
                    if (drawableBottomId != -1)
                        drawableBottom = AppCompatResources.getDrawable(context, drawableBottomId);
                    if (drawableTopId != -1)
                        drawableTop = AppCompatResources.getDrawable(context, drawableTopId);
                }
    
                // to support rtl
                setCompoundDrawablesRelativeWithIntrinsicBounds(drawableStart, drawableTop, drawableEnd, drawableBottom);
                attributeArray.recycle();
            }
        }
    }
    
  3. 이제 사용자 정의 속성으로 모든 레이아웃에서 쉽게 사용할 수 있습니다.

    <YOUR_VIEW_PACKAGE.CustomTextView
        android:id="@+id/edt_my_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:drawableStartCompat="@drawable/your_vector_drawable" <!-- vector drawable -->
        app:drawableEndCompat="@drawable/your_vector_drawable" <!-- vector drawable -->
        app:drawableTopCompat="@drawable/your_vector_drawable" <!-- vector drawable -->
        app:drawableBottomCompat="@drawable/your_vector_drawable" <!-- vector drawable -->
        />
    
    • Button , EditTextRadioButton 은 TextView에서 파생 되었으므로 비슷한 작업을 수행 할 수 있습니다

도움이 되었기를 바랍니다 :)


이 솔루션은 더 이상 정확하지 않습니다. 23.3.0 버전부터 벡터 드로어 블은 app : srcCompat 또는 setImageResource ()를 통해서만로드 할 수 있습니다.

벡터 드로어 블을 레이어 목록 또는 선택기로 래핑하십시오.

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableRight="@drawable/ic_accessible_white_wrapped"
    android:background="@color/colorPrimary"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:text="Hello World!"/>

ic_accessible_white_wrapped.xml :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_accessible_white_36px"/>
</layer-list>

내가 찾은 가장 좋은 방법 :

Drawable leftDrawable = AppCompatResources.getDrawable(this, R.drawable.ic_search);
search.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);

여기에 대한 답변 중 일부를 보완하려면 VectorDrawable을 drawableLeft(등 등) 작동하도록 할 수 있지만 지원 라이브러리 버전에 따라 다르며 가격이 제공됩니다.

어떤 경우에 작동합니까? 이 다이어그램 이 도움 되도록 만들었습니다 (지원 라이브러리 23.4.0 ~-25.1.0에 유효).

벡터 드로어 블 치트 시트


다른 답변 아무도 여기에 내가 추가 한 방법은, 일한 VectorDrawableA와를 TextView, 사용한다 VectorDrawableCompat.create()취급 할 때 VectorDrawables아래 Android L:

TextView titleTextView = (TextView) viewHolder.getView(android.R.id.text1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
       Drawable leftDrawable = AppCompatResources
                            .getDrawable(context, R.drawable.ic_tickbox);
       titleTextView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
}
else
{
      //Safely create our VectorDrawable on pre-L android versions. 
       Drawable leftDrawable = VectorDrawableCompat
                            .create(context.getResources(), R.drawable.ic_tickbox, null);
       titleTextView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
}

짧고 달콤하고 요점까지!


Google : Android 지원 라이브러리 23.3.0부터는 app : srcCompat 또는 setImageResource ()를 통해서만 지원 벡터 드로어 블을로드 할 수 있습니다.

http://android-developers.blogspot.ru/2016/02/android-support-library-232.html


XML로 벡터 드로어 블을 직접 설정할 수 있지만 데이터 바인딩 프레임 워크를 포함했습니다.

그냥 써

<TextView
...
android:drawableRight="@{@drawable/ic_accessible_white_36px}"/>

전체 레이아웃을 <layout>태그로 감싸서 기본적으로 xml은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="au.com.angryitguy.testsvg.MainActivity">


        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:drawableRight="@{@drawable/ic_accessible_white_36px}"
            android:text="Hello World!"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </RelativeLayout>
</layout>

데이터 바인딩 프레임 워크를 활성화하려면 다음을 추가하십시오.

android {
    ....
    defaultConfig {
        dataBinding {
            enabled = true
        }
    }
}

바인딩 라이브러리의 다른 기능을 사용할 필요는 없습니다.

편집하다:

물론 롤리팝 전 벡터 드로어 블을 사용하려면 다음을 사용하여 벡터 드로어 블을 지원해야합니다.

vectorDrawables.useSupportLibrary = true

따라서 build.gradle두 가지 새로운 명령이 필요합니다.

android {
    ....
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
        dataBinding {
            enabled = true
        }
    }
}

rkmax 에게 감사 의 말을 전합니다


나는이 문제에 늦게 붙어서이 질문에 대답하기에 너무 늦었습니다. TextView에서 svg / vector drawables와 동일한 문제가있었습니다. 나만의 커스텀 드로어 블을 만드는 대신, 아래처럼 두 줄의 코드로 문제를 해결할 수 있습니다 :

Drawable drawableTop = AppCompatResources.getDrawable(view.getContext(), iconId);
view.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);

그것이 당신을 도울 수 있기를 바랍니다.


모든 답변을 통해 최신 Android Studio 3.0.1 및 appcompat 지원 라이브러리 26.1.0을 사용하여 제대로 작동하는지 확인할 수 있습니다.

build.gradle (앱) 파일에서

android {
    compileSdkVersion 26
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

dependencies {
    implementation 'com.android.support:appcompat-v7:26.1.0'
}

그리고 AppcompatActivity 확장 활동 에서이 외부 메소드, 즉 정적 블록을 포함

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}  

또는 이것을 전체 앱에 적용하려면 클래스 확장 응용 프로그램 클래스 안에이 줄을 포함하십시오.

override fun onCreate() {
    super.onCreate()
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}

XML의 텍스트 뷰

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

<TextView
        android:id="@+id/passName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/account_drawableleft_selector"
        android:drawablePadding="5dp"
        android:ellipsize="marquee"
        android:fontFamily="@font/montserrat_light_family"
        android:gravity="center_vertical"
        android:marqueeRepeatLimit="marquee_forever"
        android:paddingRight="10dp"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:textColor="@color/app_text_color"
        android:textSize="12sp"
        tools:text="Account Name" />
</LinearLayout>

account_drawableleft_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_account_circle_24dp" /> <!-- checked -->
</selector>

현재의 APPCOMPAT : 1.1.0 당신은 사용할 수 있습니다

app:drawableLeftCompat
app:drawableStartCompat
...

바인딩을 사용하는 경우 TextView에서 벡터를 사용하는 동일한 방법을 사용하는 또 다른 마술 방법이 있습니다. 그들을 다음과 같이 포장 :

android:drawableLeft="@{@drawable/vector_ic_access_time_24px}"
android:drawableStart="@{@drawable/vector_ic_access_time_24px}"

그것은 마술처럼 작동 할 것입니다. 배경 뒤에서 일어나는 일을 조사하지는 않았지만 TextView가 또는 그와 비슷한 getDrawable방법을 사용하고 있다고 생각합니다 AppCompatResources.


나는 textview-rich-drawable ( 작은 drawables의 크기와 색조를 정의하는 것을 지원합니다)을 위해 작은 라이브러리를 설계했습니다 .

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Some text"
    app:compoundDrawableHeight="24dp"
    app:compoundDrawableWidth="24dp"
    app:drawableTopVector="@drawable/some_vector_drawble"
    app:drawableEndVector="@drawable/another_vector_drawable"
    app:drawableTint="@color/colorAccent" />

그리고 의존성

compile 'com.tolstykh.textviewrichdrawable:textview-rich-drawable:0.3.2'

여기에 이미지 설명을 입력하십시오


build.gradle (앱) 파일에서

android {
    compileSdkVersion 26
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }

    dataBinding {
        enabled = true
    }
}



public class BindingUtils {
    @BindingAdapter("android:drawableRight")
    public static void setDrawableStart(TextView textView, int resourceId) {
        Drawable drawable = AppCompatResources.getDrawable(textView.getContext(), resourceId);
        Drawable[] drawables = textView.getCompoundDrawables();
        textView.setCompoundDrawablesWithIntrinsicBounds(drawable,
                drawables[1], drawables[2], drawables[3]);
    } 
}

사용 (데이터 바인딩시)

android:drawableRight="@{viewModel.ResId}"

또는 (정상)

android:drawableRight="@{@drawable/ic_login_24dp}"

Behzad Bahmanyar의 답변에 따르면 일반 png 파일에 안드로이드의 일반 속성을 사용할 수 없다는 것을 알았습니다.

android:drawableTop
android:drawableBottom
etc

그것은 null로 대체되기 때문에

Drawable drawableTop = null;
...
setCompoundDrawablesRelativeWithIntrinsicBounds(drawableStart, drawableTop, drawableEnd, drawableBottom);

app:drawableTopCompat설정되지 않았지만 android:drawableTop(예 :) 인 경우

전체 솔루션은 다음과 같습니다.

public class CustomTextView extends AppCompatTextView {
    private static final int NOT_SET = -1;
    private static final int LEFT = 0;
    private static final int START = 0;
    private static final int TOP = 1;
    private static final int RIGHT = 2;
    private static final int END = 2;
    private static final int BOTTOM = 3;

    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
    }

    void initAttrs(Context context, AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        Drawable[] drawablesArr = getCompoundDrawables();

        TypedArray attributeArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
        Drawable drawableStart = null;
        Drawable drawableEnd = null;
        Drawable drawableBottom = null;
        Drawable drawableTop = null;
        Drawable drawableLeft = null;
        Drawable drawableRight = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            drawableStart = attributeArray.getDrawable(R.styleable.CustomTextView_drawableStartCompat);
            drawableEnd = attributeArray.getDrawable(R.styleable.CustomTextView_drawableEndCompat);
            drawableBottom = attributeArray.getDrawable(R.styleable.CustomTextView_drawableBottomCompat);
            drawableTop = attributeArray.getDrawable(R.styleable.CustomTextView_drawableTopCompat);
            drawableLeft = attributeArray.getDrawable(R.styleable.CustomTextView_drawableLeftCompat);
            drawableRight = attributeArray.getDrawable(R.styleable.CustomTextView_drawableRightCompat);
        } else {
            final int drawableStartId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableStartCompat, NOT_SET);
            final int drawableEndId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableEndCompat, NOT_SET);
            final int drawableBottomId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableBottomCompat, NOT_SET);
            final int drawableTopId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableTopCompat, NOT_SET);
            final int drawableLeftId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableLeftCompat, NOT_SET);
            final int drawableRightId = attributeArray.getResourceId(R.styleable.CustomTextView_drawableRightCompat, NOT_SET);

            if (drawableStartId != NOT_SET)
                drawableStart = AppCompatResources.getDrawable(context, drawableStartId);
            if (drawableLeftId != NOT_SET)
                drawableLeft = AppCompatResources.getDrawable(context, drawableLeftId);
            if (drawableEndId != NOT_SET)
                drawableEnd = AppCompatResources.getDrawable(context, drawableEndId);
            if (drawableRightId != NOT_SET)
                drawableRight = AppCompatResources.getDrawable(context, drawableRightId);
            if (drawableBottomId != NOT_SET)
                drawableBottom = AppCompatResources.getDrawable(context, drawableBottomId);
            if (drawableTopId != NOT_SET)
                drawableTop = AppCompatResources.getDrawable(context, drawableTopId);
        }

        drawableStart = (drawableStart != null ? drawableStart : drawablesArr[START]);
        drawableLeft = (drawableLeft != null ? drawableLeft : drawablesArr[LEFT]);
        drawableStart = (drawableStart != null ? drawableStart : drawableLeft);

        drawableEnd = (drawableEnd != null ? drawableEnd : drawablesArr[END]);
        drawableRight = (drawableRight != null ? drawableRight : drawablesArr[RIGHT]);
        drawableEnd = (drawableEnd != null ? drawableEnd : drawableRight);

        drawableBottom = (drawableBottom != null ? drawableBottom : drawablesArr[BOTTOM]);
        drawableTop = (drawableTop != null ? drawableTop : drawablesArr[TOP]);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setCompoundDrawablesRelativeWithIntrinsicBounds(drawableStart, drawableTop, drawableEnd, drawableBottom);
        } else {
            setCompoundDrawables(drawableStart, drawableTop, drawableEnd, drawableBottom);
        }

        attributeArray.recycle();
    }
}

벡터 드로어 블 사용

코 틀린

 val drawable1 = VectorDrawableCompat.create(resources, R.drawable.ic_rb_username, theme)
        yourView.setCompoundDrawablesRelativeWithIntrinsicBounds( drawable1, null, null, null)

자바

  Drawable drawable1 = VectorDrawableCompat.create(getResources(), R.drawable.ic_rb_username, getTheme());
        yourView.setCompoundDrawablesRelativeWithIntrinsicBounds( drawable1, null, null, null);

이전 버전과의 호환성을 위해 :

TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(textView, left, top, right, bottom)

참고 URL : https://stackoverflow.com/questions/35761636/is-it-possible-to-use-vectordrawable-in-buttons-and-textviews-using-androiddraw

반응형