【问题标题】:How to use standard attribute android:text in my custom view?如何在我的自定义视图中使用标准属性 android:text?
【发布时间】:2013-08-03 13:14:20
【问题描述】:

我编写了一个扩展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 中没有样式)?

【问题讨论】:

标签: android attributes custom-controls


【解决方案1】:

使用这个:

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

希望你有想法

【讨论】:

  • 我使用了同样的东西,但它似乎不适用于某些属性,如“textColor”。你有什么想法吗?
  • @pskink 你对stackoverflow.com/questions/24650879/… 有什么看法?
  • 一个问题。由于该重用属性不属于自定义视图(在本例中为 android:text 不属于 RelativeLayout),因此在 XML 中声明自定义视图时,它未显示在 IDE(在我的情况下为 Android Studio)的“建议”中.有没有办法让 android:text 也出现在建议中,以便用户知道这也是视图中的可用属性?
  • 这不再起作用,至少在我的 Android Studio (2.2) 版本中。当尝试使用普通的intTypedArray 上调用getText(1) 时,检查会抱怨:“预期类型为可样式化的资源”。但是,将 getText()R.styleable.MyCustomView_android_text 之类的东西一起使用是可行的。我猜 Android Studio 变得“更聪明”了
  • @sebkur 你真的运行了代码吗?如果是这样,getText() 返回什么?
【解决方案2】:

编辑

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

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。

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

【讨论】:

  • ':' 不是有效的资源名称字符。该死的。
  • @SashaNos。 ':' 在 XML 中使用,但对于代码中的资源名称,使用 '_' 代替它。看帖子的区别。如果原始帖子令人困惑或无用,我将删除它
  • 是的,我明白其中的区别。 Android Studio 只是不接受这个名称 &lt;attr name="android:text" /&gt; 因为冒号:(
  • 确实如此。我现在在我的一个项目中使用android:orientation。但是,您可能需要确保使用正确的属性名称。有效名称列表在attribute reference 中列出。
  • @J.Beck 我收到与冒号相同的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
相关资源
最近更新 更多