繁体   English   中英

如何在我的自定义视图中使用标准属性 android:text?

[英]How to use standard attribute android:text in my custom view?

我编写了一个扩展RelativeLayout自定义视图 我的观点有文字,所以我想使用标准android:text无需指定<declare-styleable>使用自定义命名空间xmlns:xxx每次我用我的自定义视图。

这是我使用自定义视图的 xml:

<my.app.StatusBar
    android:id="@+id/statusBar"
    android:text="this is the title"/>

如何获取属性值? 我想我可以获得 android:text 属性

TypedArray a = context.obtainStyledAttributes(attrs,  ???);

但什么是??? 在这种情况下(在 attr.xml 中没有样式)?

用这个:

public YourView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int[] set = {
        android.R.attr.background, // idx 0
        android.R.attr.text        // idx 1
    };
    TypedArray a = context.obtainStyledAttributes(attrs, set);
    Drawable d = a.getDrawable(0);
    CharSequence t = a.getText(1);
    Log.d(TAG, "attrs " + d + " " + t);
    a.recycle();
}

我希望你有想法

编辑

另一种方法(指定声明样式但不必声明自定义命名空间)如下:

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="android:text" />
</declare-styleable>

MyCustomView.java:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();

这似乎是从自定义视图中提取标准属性的通用 Android 方式。

在 Android API 中,他们使用内部 R.styleable 类来提取标准属性,并且似乎没有提供使用 R.styleable 提取标准属性的其他替代方法。

原帖

为了确保您从标准组件中获得所有属性,您应该使用以下内容:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextView);
CharSequence t = a.getText(R.styleable.TextView_text);
int color = a.getColor(R.styleable.TextView_textColor, context.getResources().getColor(android.R.color.darker_gray)); // or other default color
a.recycle();

如果您想要来自另一个标准组件的属性,只需创建另一个 TypedArray。

有关标准组件的可用 TypedArray 的详细信息,请参阅http://developer.android.com/reference/android/R.styleable.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM