笔记96--自定义控件系列一

来源:互联网 发布:linux pyqt5 安装 编辑:程序博客网 时间:2024/05/18 03:14

本系列大部分摘自eoe Android特刊19期。感谢eoe及其分享者。

一、概述

自定义控件两种方式:1)在已有控件的基础上,通过重写相关方法来实现我们的需求;2)继承View类或ViewGroup类,来绘制我们的控件。

以下讲解均以实例为基础。

二、RadioButton浅层需求

需求:RadioButton只能保存一个text,现在想存储key-value对应的键值对。

三、解决浅层需求

说人话:给RadioButton多一个存储key的功能。

实现逻辑:先给RadioButton增加一个属性,然后让其可被外界访问。

代码实现:

public class MRadioButton extends RadioButton implements OnCheckedChangeListener{private String mValue;public MRadioButton(Context context) {super(context);}public MRadioButton(Context context, AttributeSet attrs) {super(context, attrs);}public MRadioButton(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}public String getmValue() {return mValue;}public void setmValue(String mValue) {this.mValue = mValue;}@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {}}

四、需求加深

Android提高的控件基本上都可以在xml中设置属性,但是上面的实现貌似不可以。

五、解决加深需求

说人话:要实现上述,只需做三步:1)增加这个属性;2)告诉系统你有这个属性;3)使用这个属性。

1)增加这个属性:

即上面的getXX()、setXX()代码。

2)告诉系统你有:

先在values目录下创建attrs.xml:

<declare-styleable name="MRadioButton">        <attr name="value"  format="string"/>    </declare-styleable>
外层name表示控件名称,内存name表示属性名称,format表示类型。

然后对自定义类做部分调整(attrs中添加的属性和代码中的属性绑定):

public MRadioButton(Context context, AttributeSet attrs) {super(context, attrs);TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.MRadioButton);this.mValue=a.getString(R.styleable.MRadioButton_value);this.invalidate();a.recycle();setOnCheckedChangeListener(this);}
3)用这个属性:

先得用自己的命名空间路径,然后再使用自定义的属性。

xmlns:eoe="http://schemas.android.com/apk/res/com.example.mycontrol"
<com.example.mycontrol.MRadioButton        android:id="@+id/mRb"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world"        eoe:value="true" />
0 0
原创粉丝点击