Android自定义控件系列之基础篇
2015-04-22 15:23
169 查看
一、概述 |
二、实现定制一个简单RadioButton |
public class MRadioButton extends RadioButton { … }
2、在MRadioButton类中,定制属性
我们可以在控件中定义自己的属性,可以定义多个属性,但必须封装提供set/get方法,也就是按规范写。如mValue属性,像下面代码
private String mValue; public String getmValue() { return mValue; } public void setmValue(String mValue) { this.mValue = mValue; }
3、为定制的属性编写attrs.xml资源
该资源文件放在res/values目录下,内容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MRadioButton"> <! – 属性名称--> <attr name="value" format="string" /> </declare-styleable> </resources>
4、在MRadioButton类中定义构造函数,初始化属性
public MRadioButton(Context context) { super(context); } public MRadioButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public MRadioButton(Context context, AttributeSet attrs) { super(context, attrs); //从attrs.xml中加载一个名字叫’ .MRadioButton’的declare-styleable资源 TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MRadioButton); //将属性value与类中的属性mValue关联 this.mValue = tArray.getString(R.styleable.MRadioButton_value); //回收tArray对象 tArray.recycle(); }
5、在MainActivity中布局文件中添加MRadioButton组件,如下所示
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:jereh="http://schemas.android.com/apk/res/com.jereh. view" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.zdyview.MainActivity" > <com.itc.zidingyiview.MRadioButton android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/mrb" jereh:value="hello" /> </RelativeLayout>
6、MainActivity代码:
public class MainActivity extends Activity { private MRadioButton rb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rb=(MRadioButton)super.findViewById(R.id.mrb); rb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, rb.getmValue(),Toast.LENGTH_LONG).show(); } }); } }
[/code]
当点击单选按钮会显示hello信息
作者:杰瑞教育
出处:http://blog.csdn.net/jerehedu
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
相关文章推荐
- Android自定义控件开发系列(零)——基础原理篇
- Android自定义控件系列之基础篇
- Android自定义控件系列三:自定义开关按钮(二)
- Android基础系列之资源(三)
- OpenGLES Android篇零基础系列(四):透视投影(PerspectiveProjection)与正射投影(OrthographicProjection)
- 【Xamarin开发 Android 系列 7】 Android 结构基础(下)
- Android自定义控件系列
- Android自定义控件系列二:自定义开关按钮(一) 标签: Android自定义控件Java开关按钮自定义组件 2014-11-03 10:55 2735人阅读 评论(6) 收藏 举报 分类: J
- [Android基础系列]设计模式(二)
- Android自定义控件系列之应用篇——圆形进度条
- Android自定义控件系列一:Android如何实现老版优酷客户端三级环形菜单
- Android自定义控件系列(一)—Button七十二变
- Android自定义控件系列案例【三】
- Android基础知识总结系列(一)——Android 系统框架
- 9月黄金推荐:IT零基础系列套餐(J2EE、ASP.NET、android、hadoop、数据库、游戏开发、web前端开发)
- android自定义View基础系列一
- Android自定义控件系列案例【四】
- Android自定义控件系列一:Android如何实现老版优酷客户端三级环形菜单
- 【Android开发:自定义控件系列一】仿android4.0 Spinner下拉效果
- android基础笔记——自定义控件和视图:放ios系统开关按钮