首页 > 解决方案 > 如何从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 图像。

标签: android

解决方案


我正在尝试从 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"

推荐阅读