【问题标题】:Behavior like tools:text in a custom view?像工具这样的行为:自定义视图中的文本?
【发布时间】: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


    【解决方案1】:

    我是个骗子,骗了你们所有人。 isInEditMode() 没有返回 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 覆盖。

    呜呜呜。

    【讨论】:

    • 或者,您可以使用 if/else 语句。那会更干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多