Android(安卓)自定义控件属性赋值
1. 自定义属性
attrs.xml
文件,在AttrAssignTextView
中定义了5个属性,并且定义了一个单独的attrAssignStyle
,用于后面的定义。
2. 属性赋值
布局文件中直接定义
自定义style,在布局文件中指定View的style
style.xml
文件
自定义主题theme
3. 自定义控件
自定义控件AttrAssignTextView
public class AttrAssignTextView extends TextView { public AttrAssignTextView(Context context) { this(context, null); } public AttrAssignTextView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public AttrAssignTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AttrAssignTextView); String attr1 = a.getString(R.styleable.AttrAssignTextView_attr1); String attr2 = a.getString(R.styleable.AttrAssignTextView_attr2); String attr3 = a.getString(R.styleable.AttrAssignTextView_attr3); String attr4 = a.getString(R.styleable.AttrAssignTextView_attr4); String attr5 = a.getString(R.styleable.AttrAssignTextView_attr5); a.recycle(); setText((attr1 != null ? attr1 + "\n" : "") + (attr2 != null ? attr2 + "\n" : "") + (attr3 != null ? attr3 + "\n" : "") + (attr4 != null ? attr4 + "\n" : "") + (attr5 != null ? attr5 + "\n" : "")); }}
效果如下,布局文件定义 > style定义 > theme定义
4. defStyleAttr和defStyleRes
使用obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
方法,通过defStyleAttr
和defStyleRes
来获取默认值。
-
defStyleAttr
设置默认值,defStyleAttr
是当前Theme
中的一个attribute
,是指向style
的一个引用。重新定义主题attrAssignTheme
,添加attrAssignStyle
属性,attrAssignStyle
必须在attr
中定义过。 -
只指定
defStyleAttr
值TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AttrAssignTextView, R.attr.attrAssignStyle, 0);
效果如下,布局文件定义 > style定义 > defStyleAttr定义 > theme定义
-
只指定
defStyleRes
值TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AttrAssignTextView, 0, R.style.attrAssignDefStyleRes);
效果如下,布局文件定义 > style定义 > defStyleRes定义 > theme定义
-
同时指定
defStyleAttr
和defStyleRes
值TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AttrAssignTextView, R.attr.attrAssignStyle, R.style.attrAssignDefStyleRes);
效果如下,布局文件定义 > style定义 > defStyleRes定义 > theme定义
虽然
attrAssignDefaultStyle
中定义了attr5
,但其它地方没有定义,attr5
为空。
参考资料:http://blog.csdn.net/zq2114522/article/details/53312530
相关文章
Android 自定义控件属性
Android 自定义控件属性format详解
Android 自定义控件属性赋值
更多相关文章
- Android判断Activity是否全屏的方式!!!(最全)
- Android(安卓)Studio和MAT结合使用来分析内存问题
- Android(安卓)自定义View实现动画形式加载环形图
- Permission Denial: opening provider 隐藏的android:exported属
- [Android(安卓)Studio]设置Button的圆角、点击效果、按钮颜色
- Android如何读写CSV文件方法示例
- Android封装SDK生成Jar包以及混淆的方法
- Android(安卓)Animation动画 本文纯属抄袭 如何雷同本人一概无责
- Android获取内部和外部内存空间大小