android - 如何从textview获取drawable
问题描述
我正在尝试从 textview 获取可绘制的 Id。但我无法从 textview 获取可绘制的 Id。所以我得到了drawable并转换成位图来检查drawable。它适用于 png 图标。但是我尝试使用 VectorDrawable 我无法检查它。特此附上代码。
private void checkDrawable(int resourceId){
Drawable[] drawables = textView.getCompoundDrawables();
Bitmap bitmap = ((BitmapDrawable)drawables[0] ).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable)textView.getContext().getResources().getDrawable(resourceId)).getBitmap();
return bitmap == bitmap2;
}
这段代码工作正常。但是如果我更改为 VectorDrawable 我无法检查。
private void checkDrawable(int resourceId){
Drawable[] drawables = textView.getCompoundDrawables();
VectorDrawable bitmap = ((VectorDrawable)drawables[0]);
VectorDrawable bitmap2 = ((VectorDrawable)textView.getContext().getResources().getDrawable(resourceId));
return bitmap == bitmap2;
}
它返回不同的值。请让我有任何想法来检查 textView 中的 VectorDrawable 图像。
解决方案
我正在尝试从 textview 获取可绘制的 Id。
我将直接解决这个问题。
您可以创建自己的子类,该子类TextView
将在通货膨胀期间对其进行解析AttributeSet
并为您保留此信息。这将让您以后随时查询它。
public class MyTextView extends AppCompatTextView {
private int drawableLeftId;
private String drawableLeftEntry;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
for (int i = 0; i < attrs.getAttributeCount(); i++) {
if (attrs.getAttributeName(i).equals("drawableLeft")) {
String attributeValue = attrs.getAttributeValue(i).substring(1);
this.drawableLeftId = Integer.parseInt(attributeValue);
this.drawableLeftEntry = getResources().getResourceEntryName(drawableLeftId);
}
}
}
public int getDrawableLeftId() {
return drawableLeftId;
}
public String getDrawableLeftEntry() {
return drawableLeftEntry;
}
}
现在您可以在布局中使用它:
<com.example.stackoverflow.MyTextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/my_drawable"/>
然后您可以检索 id 和名称:
MyTextView text = findViewById(R.id.text);
int drawableLefId = text.getDrawableLeftId(); // 2131165284 (the actual value of R.drawable.my_drawable)
String drawableLeftEntry = text.getDrawableLeftEntry(); // "my_drawable"
推荐阅读
- python - pymc3:截断正常混合
- android - Unity3D Android Crunch 压缩文件大小混乱
- sql - 我不能做学校作业。需要 SQLite 帮助
- algorithm - 约翰逊算法,其中从源到其他节点的距离不为零
- html - 使用 justify-content: space-evenly 时如何不向左溢出
- ios - 在为 iOS 颤振创建构建时面临问题
- python-3.x - mongodb 通过使用公共字段和值组合 2 个或多个文档进行过滤
- python - I want to find the input checkbox and click with selenium (python)
- eclipse - 带有 Ear、War 项目节点的 Eclipse Maven 项目
- react-native - React Navigation 5 - 将参数传递到选项卡屏幕