自定义组合控件
1.创建自定义控件继承RelativeLayout
public class SettingView extends RelativeLayout {
2.创建一个init方法,并在每个构造函数中调用
/**
* 添加控件
*/
private void init(){
//添加布局文件
// TextView textView = new TextView(getContext());
// textView.setText("我是自定义组合控件的textview");
//第一种方式
//将布局文件转化成view对象
// View view = View.inflate(getContext(), R.layout.settingview, null);//爹有了,去找孩子,亲生
// //添加操作
// this.addView(view);//在自定义组合控件中添加一个textview
//第二种方式
//获取view对象,同时给veiw对象设置父控件,相当于先创建一个view对象,在把控件放到自定义控件中
View.inflate(getContext(), R.layout.settingview, this);//孩子有了,去找爹,喜当爹
}
自定义属性
1.在values->attrs.xml<resources>
<declare-styleable name="包名.ui.SettingView">
<attr name="title" format="string" /><!-- name:属性的名称,format:类型 -->
<attr name="des_on" format="string" />
<attr name="des_off" format="string" />
</declare-styleable>
布局中使用
a.命名空间
xmlns:itheima=”http://schemas.android.com/apk/res/包名”
b.控件中使用
<包名.ui.SettingView
android:id=”@+id/sv_setting_update”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
itheima:title=”提示更新”
itheima:des_on=”打开提示更新”
itheima:des_off=”关闭提示更新”
String title = attrs.getAttributeValue("http://schemas.android.com/apk/res/包名", "title");
des_on = attrs.getAttributeValue("http://schemas.android.com/apk/res/包名", "des_on");
des_off = attrs.getAttributeValue("http://schemas.android.com/apk/res/包名", "des_off");
//给自定义组合控件的控件设置相应的值
//初始化控件的值
tv_setting_title.setText(title);
if (isChecked()) {
tv_setting_des.setText(des_on);
}else{
tv_setting_des.setText(des_off);
}