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