6

在自定义TextView中,我试图获取text属性的值(例如)。

TypedArray values = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView);
String text = values.getString(com.android.internal.R.styleable.TextView_text);

但我收到此错误消息:

包 com.android.internal.R 不存在

那么如何检索 TextView 的“默认”属性呢?

4

4 回答 4

7

如果您想访问那些“android”属性,您可以“覆盖”它们:在您的 declarable-styleable 声明中,例如。

<attr name="android:padding"/>

然后您可以通过以下方式轻松获得它:

int padding = a.getInt(R.styleable.CustomView_android_padding, -1);

只是为了记录 anwser 的灵感来自 Lucas Rocha 实现的 TwoWayView 布局的源代码。我认为这是一个很好的例子来分析如何实现自定义视图

于 2014-12-12T15:11:29.273 回答
1

internal.R 类是不可见的,因此您只能通过它们的访问器方法读取它们,并且只有在调用超级构造函数后才能读取它们。

查看TextView 源代码以了解它在内部是如何工作的。

于 2014-10-21T14:10:44.523 回答
0

例子:

val attrsArray = intArrayOf(android.R.attr.digits, android.R.attr.text)
val ta = context.obtainStyledAttributes(attrs, attrsArray)
val digits = ta.getString(0)
val text = ta.getText(1)
ta.recycle()
于 2021-12-29T08:10:16.767 回答
-1

要访问com.android.internal.R的资源,您可以使用

Resources.getSystem().getIdentifier(name, defType, defPackage)

链接可能会有所帮助:

于 2015-05-28T16:34:38.647 回答