自定义控件. android
1,写一个自定义控件类继承系统的一个布局.(5大布局) ,重写3个构造方法 定义checked方法判断当前自定义控件是否被选中(若是自定义控件里面有CheckBox,能够把CheckBox找到,判断它是否被选中)
能够再写一个方法来设置当前控件的选中状态:setChecked(); 要更改里面的内容还要写方法 数组
2,在res_layout目录下建立layout:你要显示的样式,注意:若是里面有checkbox,须要注意他的点击和焦点 app
3,用View.inflate(context, R.layout.view_setting, this); //把xml文件转化成对象,this:view对象以本身为父体 在三个构造方法中都要调用 布局
4,在要用到自定义控件的layout.xml文件里面放入自定义控件,节点名称是自定义控件类的全名
<com.example.myapplication.SettingView
android:id="@+id/sv_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
this
5,在value目录下建立一个attrs.xml文件,里面建立自定义控件的属性
<declare-styleable name="my_setting_view">
<attr name="title" format="string" /> //title属性是string类型
<attr name="content" format="string" />
</declare-styleable>
6,在activity中要使用自定义控件,就要在它的layout.xml中声明本身的名称空间:
在 xmlns:android="http://schemas.android.com/apk/res/android" 后添加本身的名称空间
xmlns:xxx="http://schemas.android.com/apk/res/cn.xxx.mobilesafe"
这时就能够在自定义的控件里面设置它的属性,以下:
<com.example.myapplication.SettingView
android:id="@+id/sv_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xxx:title = "我是标题"
xxx:content = "我是内容"/>
7,在自定义控件类中的构造方法里面: orm
//把属性集和咱们定义的属性数组创建对应关系
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.my_setting_view);
String content = a.getString(R.styleable.my_setting_view_content);
String title = a.getString(R.styleable.my_setting_view_title);
tv_title.setText(title); //控件tv_title须要在view.inflate()后findViewbyId找到控件
tv_content.setText(content);
a.recycle();
8,在Activity代码中找到自定义控件,进行操做 xml