行为像工具:自定义视图中的文本? [英] Behavior like tools:text in a custom view?
问题描述
我有一个自定义视图,在布局中有两个文本视图.我们称一个key
和另一个value
.
I have a custom view with two text views in the layout. Let's call one key
and the other value
.
所以您知道TextView
的情况如何?
So you know how TextView
has this?
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Preview text shown in the layout editor" />
我想对自定义视图执行类似的操作,例如:
I want to do something similar with my custom view, e.g.:
<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 :("
则什么也没有显示.
The issue is that isInEditMode()
is returning false
when I view a layout which includes MyCustomView
in the layout editor. If I add app:key="yay"
it works fine, but for app:key_preview="nay :("
nothing shows up.
有什么作用?
推荐答案
我是丁格,对所有人撒谎. isInEditMode()
没有返回false.
I am a dingus and lied to you all. isInEditMode()
was not returning false.
咳嗽咳嗽:
if (isInEditMode()) {
key.setText(a.getText(R.styleable.MyCustomView_key_preview));
value.setText(a.getText(R.styleable.MyCustomView_value_preview));
} else {
key.setText(a.getText(R.styleable.MyCustomView_key));
value.setText(a.getText(R.styleable.MyCustomView_value));
}
原来我实际上将键设置为app:key_preview
的值,但是随后又用a.getText(R.styleable.MyCustomView_key)
返回的null
覆盖了它.
Turns out what I had initially was in fact setting the key to be the value of app:key_preview
, however it was then subsequently overwritten with the null
that a.getText(R.styleable.MyCustomView_key)
was returning.
voopz.
这篇关于行为像工具:自定义视图中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!