是否可以使用android:DrawableRight在Button和TextViews中使用VectorDrawable?


120

当我在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'
}

这是崩溃。(请注意引用textview的膨胀错误。)

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

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

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

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

不,您不能,因为SVG文件本身不受支持。您必须改为使用VectorDrawable(仅使用SVG规范的子集)。
Phantômaxx

2
要了解如何将VectorDrawable与drawableLeft,drawableRight,drawableTop,drawableBottom结合使用,请查看此答案
Behzad Bahmanyar 2016年

我发现这对我有用
惠塔

Answers:


186

是否可以对SVG资产使用drawableRight等?

AppCompatTextView 现在支撑件app:drawableLeftCompatapp:drawableTopCompatapp:drawableRightCompatapp:drawableBottomCompatapp:drawableStartCompatapp:drawableEndCompat化合物可绘,支持向后移植可拉伸类型,例如VectorDrawableCompat

将此包含在您的gradle文件中

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

在文本视图中,您可以使用

app:drawableLeftCompat
app:drawableStartCompat

如果在使用app:drawableLeftCompat,app:drawableStartCompat按钮时遇到问题,则需要将库更新为

androidx.appcompat:appcompat:1.2.0-alpha01

他们有一个错误

androidx.appcompat:appcompat:1.1.0-alpha01

你可以看到文档


或者,如果您不想更新,则:

由于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 -->
        />
    • 您可以使用ButtonEditTextRadioButton进行类似的操作,因为它们派生自TextView

希望这可以帮助 :)


4
非常有用的答案。无论如何,我建议您也阅读大豆的完整答案vectorDrawables { useSupportLibrary = true }从我的build.gradle回答中删除就可以为我工作。
山姆

我做到了,现在有以下问题:当我在XML中附加onclick时,出现以下错误:java.lang.NoSuchMethodException:onClick [class android.view.View]
Ramdane Oualitsen

3
我不同意将vectorDrawables useSupportLibrary = true线从gradle中删除。删除它后,您仍然可以在视图中放置矢量,但是它们的大小与png相同,这意味着它们将被拉伸并变成颗粒状。如果要使5.0 / API21以下的设备实际正确调整矢量的大小,使它们看起来清晰,则必须在gradle文件中使用该行。将该行放入会调用IDE来查找您不正确使用矢量的区域,然后必须使用app:srcCompatvia XML或通过以下代码通过代码进行设置VectorDrawableCompat.create()
Heinous Games

如何添加app:drawableEndCompat以获得更好的RTL支持?原因setCompoundDrawablesRelativeWithIntrinsicBounds至少需要API级别17。
Dr.jacky

1
如何以编程方式设置可绘制对象?
Android开发人员

77

该解决方案不再正确。从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>

这很好。谢谢..但是看来您不能直接在“ android:drawableXXXXX”中引用SVG,而必须将其包装在其他内容中。
AngryITguy

1
是。您不能直接使用它。仅作为app:srcCompat或以包装方式或通过编程方式包装。这是说明如下:android-developers.blogspot.ru/2016/02/...
亚历山大Shutko

嗯..谢谢..我可以看到您所指的段落。因此,如果他们告诉您不要这样做,那仍然是一个错误吗?;)
AngryITguy

1
我认为这全都是向后兼容。获得全面的svg支持似乎有些问题,因此他们
采取

2
支持版本23.3.0的@HarishGyanani,已不再支持。您必须在活动中添加更多命令:静态{如果(Build.VERSION.SDK_INT <Build.VERSION_CODES.LOLLIPOP){AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); }
阮阮

75

我发现的最好方法:

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

9
从17年8月25日开始,这是唯一对我有用的内容(以编程方式设置可绘制对象)。我实际上使用过:Drawable drawable = VectorDrawableCompat.create(getResources(), status.getIconResId(), wrapper.getTheme()); statusButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);
saiyancoder

2
minSdk的setCompoundDrawablesWithIntrinsicBounds17。否则,这很好。
维克托·伦迪纳

1
它的minSdk是1而不是17,您可能会看到类似的api。setCompoundDrawablesWithIntrinsicBounds => minSdk 1; setCompoundDrawablesRelativeWithIntrinsicBounds => minSdk 17
正宗白布鞋

以编程方式设置的最佳解决方案,+ 1
Woton Sampaio,

我将此与BindingAdapters一起使用并有效地工作,谢谢!
Ric17101 '18 -10-23

61

为了补充此处的一些答案:您可以使VectorDrawable像drawableLeft(等)一样工作,但是它取决于支持库版本,并且附带价格。

在什么情况下有效?我制作了此图以提供帮助(对于支持库23.4.0至-至少-25.1.0有效)。

VectorDrawable备忘单


2
很棒,但是您应该将静态块中的方法名称更正为setCompatVectorFromResourcesEnabled
Vikas Patidar '17

1
不幸的是,setCompatVectorFromResourcesEnabled解决方案不适用于25.3.1
Ilja

From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource()因此,此解决方案已被弃用,将无法使用
user25

启用后setCompatVectorFromSourcesEnabled(true),就可以android:background在Android 4.x上加载vectordrawables了。那谢谢啦!(您确实需要将实际矢量包装在单个项目的层列表中)
Peterdk,

14

其他答案均无效,这是我在中添加a VectorDrawable的方式TextViewVectorDrawableCompat.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);
}

简短,甜美,直指重点!


这适用于Android P和最低API级别26(目标28)
MiStr

@MiStr-它也向后兼容:)
Sakiboy

9

来自Google:自Android支持库23.3.0起,支持矢量可绘制对象只能通过app:srcCompat或setImageResource()加载。

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


1
这意味着目前没有解决方案
Killer

尝试将可绘制的矢量包装到图层列表或选择器中:<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 =“ schemas .android.com / apk / res / android “> <item android:drawable =” @ drawable / ic_accessible_white_36px“ /> </ layer-list>
空指针异常

9

可以在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需要2条新命令:

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

感谢rkmax的发言


这是一个好主意,但是您需要编写一个绑定适配器才能使它起作用。这是一个工作示例:gist.github.com/lisawray/78c33f76809d2bcbbec9983e2c141a70
BladeCoder 16-10-25

1
我必须说这对我vectorDrawables.useSupportLibrary有用,但是您必须在app / build.gradle上启用,还必须在活动上添加AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
rkmax,2016年

我忘记在其中添加defaultConfig,build.gradle这可能是它无法正常工作的原因
Hans M

谢谢-您是救生员!

这是一个被低估的答案!
DYS

6

我仔细研究了所有答案,并使用了最新的Android Studio 3.0.1和AppCompat支持库26.1.0,我可以保证一切正常。

build.gradle(app)文件中

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

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

在活动扩展中,AppcompatActivity包括此外部方法,即一个static

static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}  

或者如果您希望将其应用于整个应用程序,则只需在扩展Application类的类中包含此行

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

xml中的T​​extview

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

在什么API上工作正常?您尝试过19还是20?
Divers

你能告诉你如何使用drawableRightTextViewXML格式?
Divers

2
像上面提到的少数几个一样,如果您直接将vector xml用作drawableLeft,则仍然会发生此崩溃或异常,因此解决方法是将vector xml用作Textview的drawableLeft的选择器。您可以在修改后的答案中看到用法。
阿米特·图姆库

1
它行不通,您不能直接在xml中为TextView使用vector drawable
user25

在API 19和20中对其进行测试。我在应用程序类中使用了AppCompatDelegate.setCompatVectorFromResourcesEnabled。像魅力一样工作!
Red M


5

我回答这个问题太迟了,因为我坚持这个问题很晚。我在使用TextView的svg / vector drawables中遇到了相同的问题。不用制作自己的自定义可绘制对象,我可以用两行代码来解决我的问题,如下所示:

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

希望它能对您有所帮助。


与前置L设备不兼容。
Sakiboy '17

@Sakiboy是的,因为我使用的代码最少为api17。–
Rahul Sharma

VectorDrawables只是说一下,并非适用于所有运行pre-L的设备。使用此答案时请务必谨慎,因为有更安全,更准确的API可供使用。
Sakiboy

4

我为此设计了一个微型库-textview-rich-drawable(它还支持定义复合可绘制对象的大小和着色)。

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

在此处输入图片说明


3

如果您使用绑定,则还有另一种神奇的方法可以使在TextView中使用矢量的方法相同。像这样包装它们:

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

这将神奇地起作用,我还没有调查幕后发生的事情,但是我想TextView正在使用或类似getDrawable方法AppCompatResources


2

基于Behzad Bahmanyar的回答,我注意到我无法对普通png文件使用android的normal属性:

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();
    }
}

这应该被接受。使用普通的png文件和属性drawableTop,drawableBottom。可接受的答案不适用于png文件和drawableTop,drawableBottom属性。
巴尔加潘迪亚

2

在build.gradle(app)文件中

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}"

1

使用Vector Drawables使用

科特林

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

1

为了向后兼容,请使用:

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

0

我正在使用绑定适配器来解决此问题

@JvmStatic
@BindingAdapter("drawableSvgLeft")
fun addDrawableSvgLeft(textView: TextView,drawable: Drawable){
    textView.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null)
}

@JvmStatic
@BindingAdapter("drawableSvgRight")
fun addDrawableSvgRight(textView: TextView,drawable: Drawable){
    textView.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable,null)
}

并以这种方式在我的布局中使用

<TextView
  drawableSvgRight="@{@drawable/svg_ic_battle_trophy}"
  .....

默认情况下可能需要vectorDrawables.useSupportLibrary = true

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.