hos*_*ini 5 android android-widget custom-view android-custom-view android-attributes
我创建了一个简单的自定义视图,其中包含a RelativeLayout和EditText:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edt_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
此外,我添加了一些自定义属性res/values/attrs.xml,我在自定义视图构造函数中检索这些属性,一切正常.
现在,我想EditText在自定义视图中检索默认属性,例如我想android:text在自定义视图中获取属性.
我的自定义视图类(简化):
public class CustomEditText extends RelativeLayout {
private int panCount;
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.CustomEditText, 0, 0);
try {
this.panCount = typedArray.getInt(R.styleable.CustomEditText_panCount, 16);
} finally {
typedArray.recycle();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果不重新声明文本属性,我怎么能这样做res/values/attrs.xml呢?
tyn*_*ynn 15
您可以添加android:text到声明的syleable.但一定不要重新声明它.
<declare-styleable name="CustomEditText">
<attr name="android:text" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
然后从样式中获取此值,就像使用索引为的任何其他属性一样R.styleable.CustomEditText_android_text.
CharSequence text = typedArray.getText(R.styleable.CustomEditText_android_text);
Run Code Online (Sandbox Code Playgroud)