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

Ser*_*m's 59 android attributes custom-controls

我写了一个扩展的自定义视图RelativeLayout.我的视图有文本,所以我想使用标准,android:text 而不需要在每次使用自定义视图时指定<declare-styleable>使用自定义命名空间xmlns:xxx.

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

<my.app.StatusBar
    android:id="@+id/statusBar"
    android:text="this is the title"/>
Run Code Online (Sandbox Code Playgroud)

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

TypedArray a = context.obtainStyledAttributes(attrs,  ???);
Run Code Online (Sandbox Code Playgroud)

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

psk*_*ink 87

用这个:

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();
}
Run Code Online (Sandbox Code Playgroud)

我希望你有个主意

  • 我使用了相同的东西,但它似乎不适用于某些属性,如'textColor'.你有什么主意吗? (3认同)
  • 一个问题.由于该重用属性不属于自定义视图(在本例中为android:text不属于RelativeLayout),因此在XML中声明自定义视图时,它不会显示在IDE(我的案例中为Android Studio)的"建议"中.有没有办法使android:文本出现在建议中,所以用户知道这也是视图中的可用属性? (2认同)
  • 这不再起作用,至少在我的 Android Studio (2.2) 版本中是这样。当尝试使用简单的 `int` 调用 `TypedArray` 上的 `getText(1)` 时,检查会抱怨:“预期的 styleable 类型资源”。但是,将 `getText()` 与类似 `R.styleable.MyCustomView_android_text` 的内容一起使用是有效的。我猜 Android Studio 变得“更聪明”了 (2认同)

J. *_*eck 39

编辑

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

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="android:text" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

MyCustomView.java:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
CharSequence t = a.getText(R.styleable.MyCustomView_android_text);
a.recycle();
Run Code Online (Sandbox Code Playgroud)

这似乎是从自定义视图中提取标准属性的通用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();
Run Code Online (Sandbox Code Playgroud)

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

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