有的时候我们需要自定义自己的控件属性(在自定义View中使用)
可以参照官方例子去做
1.,创建自己属性文件,res/values/attrs.xml
:
例子如下:
<declare-styleable name="CustomLayoutLP"> <attr name="android:layout_gravity" /> <attr name="layout_position"> <enum name="middle" value="0" /> <enum name="left" value="1" /> <enum name="right" value="2" /> </attr> </declare-styleable>这里的CustomlayoutLP为该自定义属性的名称,以后会在代码中用到,
两个<attr>节点为属性节点,在这里添加自己的属性
2.修改布局文件
例子如下:
<com.example.android.apis.view.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- put first view to left. --> <TextView android:background="@drawable/filled_box" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_position="left" android:layout_gravity="fill_vertical|center_horizontal" android:text="l1"/>注意这里的xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"
这个是你的属性的命名控件,其中app为属性前缀,与平常的"android"类似,com.example.android.apis为你的应用的包名(在manifest文件中可见)
修改这两处过后就可以在你的控件中添加自己的属性值
3.在自定义属性中获取自己的属性值:
例子如下:
public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); // Pull the layout param values from the layout XML during // inflation. This is not needed if you don't care about // changing the layout behavior in XML. TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.CustomLayoutLP); gravity = a.getInt(R.styleable.CustomLayoutLP_android_layout_gravity, gravity); position = a.getInt(R.styleable.CustomLayoutLP_layout_position, position); a.recycle(); }前面1中的属性的名称在这里用到,获取属性的格式为: 属性名_属性值名
记得最后recyle一下,可能以后需要重用