Java 是否可以使用 android:DrawableRight 在 Buttons 和 TextViews 中使用 VectorDrawable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35761636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use VectorDrawable in Buttons and TextViews using android:DrawableRight?
提问by angryITguy
When I use VectorDrawable assets in a textview or imageview I get a runtime crash when using "android:DrawableRight" / "android:DrawableEnd" / "android:DrawableStart" / "android:DrawableLeft".
当我在 textview 或 imageview 中使用 VectorDrawable 资产时,我在使用“android:DrawableRight”/“android:DrawableEnd”/“android:DrawableStart”/“android:DrawableLeft”时出现运行时崩溃。
The app will compile fine without any warnings.
该应用程序将编译正常,没有任何警告。
I am using
我在用
- Gradle 1.5
- Support Library 23.2 ('com.android.support:appcompat-v7:23.2.0')
- 摇篮 1.5
- 支持库 23.2 ('com.android.support:appcompat-v7:23.2.0')
What I have found though is that I can programmatically assign SVG's in Java without crashes like this.
不过我发现我可以在 Java 中以编程方式分配 SVG,而不会出现这样的崩溃。
TextView tv = (TextView) findViewById(R.id.textView);
tv.setCompoundDrawablesWithIntrinsicBounds(null,null, getResources().getDrawable(R.drawable.ic_accessible_white_36px),null);
(I suspect this is a support library bug for 23.2.)
(我怀疑这是 23.2 的支持库错误。)
But is it possible to use drawableRight etc for SVG assets ?
但是是否可以将 drawableRight 等用于 SVG 资产?
Here is my layout
这是我的布局
<?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>
Here is my Activity
这是我的活动
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);
}
}
Here is the unmodified VectorDrawable asset from Google's material design site.
这是来自 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>
Here is my app build.gradle
这是我的应用程序 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'
}
Here is the crash. (Note the inflate errors that reference the textview.)
这是崩溃。(注意引用 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.access0(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)
...
采纳答案by Behzad Bahmanyar
it possible to use drawableRight etc for SVG assets ?
可以将 drawableRight 等用于 SVG 资产吗?
Yes
是的
AppCompatTextViewnowsupports app:drawableLeftCompat
, app:drawableTopCompat
, app:drawableRightCompat
, app:drawableBottomCompat
, app:drawableStartCompat
and app:drawableEndCompat
compound drawables, supporting backported drawable types such as VectorDrawableCompat
.
AppCompatTextView现在支撑件app:drawableLeftCompat
,app:drawableTopCompat
,app:drawableRightCompat
,app:drawableBottomCompat
,app:drawableStartCompat
和app:drawableEndCompat
化合物可绘,支持向后移植可拉伸类型,例如VectorDrawableCompat
。
Include this in your gradle file
将此包含在您的 gradle 文件中
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
In your text view you can use
在您的文本视图中,您可以使用
app:drawableLeftCompat
app:drawableStartCompat
If you have problems while using app:drawableLeftCompat, app:drawableStartCompat in buttons you will need to update your library to
如果在按钮中使用 app:drawableLeftCompat、app:drawableStartCompat 时遇到问题,则需要将库更新为
androidx.appcompat:appcompat:1.2.0-alpha01
androidx.appcompat:appcompat:1.2.0-alpha01
they had a bug on
他们有一个错误
androidx.appcompat:appcompat:1.1.0-alpha01
androidx.appcompat:appcompat:1.1.0-alpha01
you can see the docs
你可以看到文档
Or if you don't want to update yet, then:
或者,如果您还不想更新,则:
Because it seems Google not going to do anything about this issue any time soon, I had to came up with a more solid reusable solution for all of my apps:
因为 Google 似乎不会很快就这个问题做任何事情,所以我不得不为我的所有应用程序想出一个更可靠的可重用解决方案:
First add custom TextViewattributes in attrs.xml file of your app "res/values/attrs.xml":
<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>
Then create custom TextView class like this:
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(); } } }
Now you can use it easily in any layouts by your custom attributes:
<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 --> />
- You can do similar thing with Button, EditTextand RadioButtonbecause they derived from TextView
首先在应用"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>
然后像这样创建自定义 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(); } } }
现在,您可以通过自定义属性在任何布局中轻松使用它:
<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、EditText和RadioButton做类似的事情,因为它们派生自 TextView
Hope this helps :)
希望这可以帮助 :)
回答by Alexandr Shutko
This solution is no longer correct. From 23.3.0 version vector drawables can only be loaded via app:srcCompat or setImageResource()
此解决方案不再正确。从 23.3.0 版本开始,矢量可绘制对象只能通过 app:srcCompat 或 setImageResource() 加载
Try to wrap your vector drawable into layer-list or selector:
尝试将您的矢量 drawable 包装到图层列表或选择器中:
<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:
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>
回答by paulzeng
From Google: As of Android Support Library 23.3.0, support vector drawables can only be loaded via app:srcCompat or setImageResource()..
来自 Google:从 Android 支持库 23.3.0 开始,支持向量可绘制对象只能通过 app:srcCompat 或 setImageResource() 加载。
http://android-developers.blogspot.ru/2016/02/android-support-library-232.html
http://android-developers.blogspot.ru/2016/02/android-support-library-232.html
回答by Hans M
It is possible to directly set vector drawables in xml, but you have include the data binding framework.
可以直接在 xml 中设置矢量可绘制对象,但您必须包含数据绑定框架。
Just write
写就好了
<TextView
...
android:drawableRight="@{@drawable/ic_accessible_white_36px}"/>
and wrap your whole layout in a <layout>
tag, so basically your xml would look like:
并将整个布局包装在一个<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>
To activate the data binding framework just add
要激活数据绑定框架,只需添加
android {
....
defaultConfig {
dataBinding {
enabled = true
}
}
}
You don't have to use any other features of the binding library
您不必使用绑定库的任何其他功能
EDIT:
编辑:
Of course if you want to use vector drawables pre-Lollipop your have to enable support vector drawables using
当然,如果您想在 Lollipop 之前使用矢量可绘制对象,则必须使用以下方法启用支持向量可绘制对象
vectorDrawables.useSupportLibrary = true
vectorDrawables.useSupportLibrary = true
So your build.gradle
needs 2 new commands:
所以你build.gradle
需要 2 个新命令:
android {
....
defaultConfig {
vectorDrawables.useSupportLibrary = true
dataBinding {
enabled = true
}
}
}
thanks to rkmaxfor the remark
感谢rkmax的评论
回答by cesards
If you are using binding, there is another magic way to have the same approach to use vectors in a TextView. Wrapping them like:
如果您正在使用绑定,还有另一种神奇的方法可以使用相同的方法在 TextView 中使用向量。像这样包装它们:
android:drawableLeft="@{@drawable/vector_ic_access_time_24px}"
android:drawableStart="@{@drawable/vector_ic_access_time_24px}"
That will magically work, I haven't investigated what's happening behind the scenes, but I guess the TextView is using the getDrawable
method from the AppCompatResources
or similar.
这会神奇地起作用,我还没有调查幕后发生的事情,但我猜 TextView 正在使用或类似的getDrawable
方法AppCompatResources
。
回答by Hani
The best way I found:
我发现的最好方法:
Drawable leftDrawable = AppCompatResources.getDrawable(this, R.drawable.ic_search);
search.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, null, null);
回答by David Ferrand
To complement some of the answers here: you can get VectorDrawable to work as drawableLeft
(etc.) but it depends on the Support Library version and it comes with a price.
为了补充这里的一些答案:您可以让 VectorDrawable 像drawableLeft
(等)那样工作,但这取决于支持库版本,并且需要付出一定的代价。
In which cases does it work? I've made this diagramto help (valid for Support Library 23.4.0 to - at least - 25.1.0).
在哪些情况下有效?我制作了这张图来提供帮助(对于支持库 23.4.0 到 - 至少 - 25.1.0 有效)。
回答by Rahul Sharma
I am so late to answer this question as I stucked late with this problem. I had the same issue with svg/vector drawables with TextView. Instead of making your own custom drawable I am able to fix my problem with 2 lines of code as below:
我回答这个问题太晚了,因为我在这个问题上迟到了。我对带有 TextView 的 svg/vector drawable 有同样的问题。我可以使用以下两行代码解决我的问题,而不是制作自己的自定义可绘制对象:
Drawable drawableTop = AppCompatResources.getDrawable(view.getContext(), iconId);
view.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
Hope it will help you out.
希望它能帮到你。
回答by Sakiboy
None of the other answers worked, here's how I've added a VectorDrawable
to a TextView
, you should use VectorDrawableCompat.create()
when dealing with VectorDrawables
below Android L
:
其他答案均无效,这是我将 a 添加VectorDrawable
到 a 的方法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);
}
Short, sweet, and to the point!
简短,甜蜜,切中要害!
回答by Oleksandr
I've designed a tiny library for this - textview-rich-drawable(it also supports defining the compound-drawables' size and tinting).
我为此设计了一个小库 - 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" />
And the dependency
和依赖
compile 'com.tolstykh.textviewrichdrawable:textview-rich-drawable:0.3.2'