レイアウトに2つのテキストビューを持つカスタムビューがあります。 1つをkey
とし、もう1つを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 :("
の場合は何も表示されません。
何がありますか?
代わりに、if/elseステートメントを使用することもできます。それはより清潔になります。 – fsociety
を編集する^ – fsociety