如何在自定义TextView中获取名称空间"android"的属性

Dim*_*ima 5 android textview android-custom-view android-custom-attributes

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

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

但我收到此错误消息:

包com.android.internal.R不存在

那么如何检索TextView的"默认"属性?

Krz*_*cki 6

如果你想要访问那些'android'属性,你可以'覆盖'它们:在你声明的样式声明中,例如.

<attr name="android:padding"/>
Run Code Online (Sandbox Code Playgroud)

然后你可以这样轻松地获得它:

int padding = a.getInt(R.styleable.CustomView_android_padding, -1);
Run Code Online (Sandbox Code Playgroud)

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


小智 1

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

请参阅TextView 源代码以了解其内部工作原理。