Behavior like tools:text in a custom view?

≯℡__Kan透↙ 提交于 2019-12-08 07:14:29

问题


I have a custom view with two text views in the layout. Let's call one key and the other value.

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" />

The constructor for MyCustomView is like so:

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

And 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>

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.

What gives?


回答1:


I am a dingus and lied to you all. isInEditMode() was not returning false.

cough cough:

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

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.



来源:https://stackoverflow.com/questions/42770383/behavior-like-toolstext-in-a-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!