代码之家  ›  专栏  ›  技术社区  ›  Vijayadhas Chandrasekaran

如何从textview获取可绘制的

  •  0
  • Vijayadhas Chandrasekaran  · 技术社区  · 7 年前

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

    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中的矢量绘图图像。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ben P.    7 年前

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