笔记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
- 笔记96--自定义控件系列一
- 自定义控件自学笔记(一)
- Android自定义控件系列案例【一】
- 笔记97--自定义控件系列二
- 自定义控件学习笔记(一)Canvas 的 drawXXX() 系列方法
- UserControl自定义控件系列一:Label+TextBox组合控件
- Android自定义控件系列一:如何测量控件尺寸
- Android自定义控件系列二:自定义开关按钮(一)
- Android自定义控件系列二:自定义开关按钮(一)
- Android自定义控件系列二:自定义开关按钮(一)
- Android自定义控件系列二:自定义开关按钮(一)
- 自定义控件学习笔记(一)
- Android自定义控件开发笔记<一>
- 【自定义控件系列一】android画图类---Canvas浅谈
- Android自定义控件系列(一)—Button七十二变
- Android自定义控件开发系列(一)——第一次动手做自定义控件
- Android自定义控件开发系列(一)——第一次动手做自定义控件
- 笔记99--自定义控件系列大结局三
- 2015当前最火的web开发技术
- php扩展开发
- 好网站 统计之都:http://cos.name/
- UI-UISegmentedControl
- java学习day07
- 笔记96--自定义控件系列一
- 九大Java性能优化工具帮你轻松搞定Java代码
- 虚拟网络的无损保证-zOVN
- 【算法设计与分析】8、哈弗曼编码,贪心算法实现
- List Components
- 关于集合的使用
- Eclipse,Myeclipse增强代码提示功能
- iOS程序的执行顺序 和 UIViewController的生命周期
- 四个经典的SQL编程问题 (希望对你有帮助)