【发布时间】:2017-03-13 17:59:19
【问题描述】:
我有一个自定义视图,布局中有两个文本视图。我们打电话给一个key 和另一个value。
那么你知道TextView 是怎么做到的吗?
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Preview text shown in the layout editor" />
我想对我的自定义视图做类似的事情,例如:
<com.package.whatever.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:key_preview="Preview text for the key"
app:value_preview="Preview text for the value" />
MyCustomView 的构造函数是这样的:
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.my_custom_view, this, true);
key = (TextView) findViewById(R.id.key);
value = (TextView) findViewById(R.id.value);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
try {
if (isInEditMode()) {
key.setText(a.getText(R.styleable.MyCustomView_key_preview));
value.setText(a.getText(R.styleable.MyCustomView_value_preview));
}
key.setText(a.getText(R.styleable.MyCustomView_key));
value.setText(a.getText(R.styleable.MyCustomView_value));
} finally {
a.recycle();
}
}
还有attrs.xml:
<declare-styleable name="MyCustomView">
<attr name="key" format="string" />
<attr name="key_preview" format="string" />
<attr name="value" format="string" />
<attr name="value_preview" format="string" />
</declare-styleable>
问题是当我在布局编辑器中查看包含 MyCustomView 的布局时,isInEditMode() 正在返回 false。如果我添加 app:key="yay" 它可以正常工作,但对于 app:key_preview="nay :(" 没有任何显示。
什么给了?
【问题讨论】:
标签: android android-layout android-custom-view android-xml