自定义组合控件:textView+checkBox
先实现布局文件ui_setting_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_set_update"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_gravity="center_vertical"
android:background="@drawable/background" >
<TextView
android:id="@+id/tv_ui_setting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:text="开启自动更新"
android:textSize="25sp" />
<CheckBox
android:id="@+id/cb_set_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:clickable="false"
android:focusable="false" />
<View //一条线
android:layout_width="match_parent"
android:layout_height="0.1dp"
android:layout_marginTop="1dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:layout_below="@id/tv_ui_setting"
android:layout_margin="2dp"
android:background="#88000000" />
</RelativeLayout>
定义一个类继承LinearLayout ,实现父类的构造函数,初始化控件,加上一个判断是否勾选的函数,还有一个设置Checkbox勾选的函数
public class SettingCheckView extends LinearLayout {
private CheckBox set_update;
public SettingCheckView(Context context, AttributeSet attrs) {
super(context, attrs);
initial(context);
//获取属性定义的文本
String bigtitle=attrs.getAttributeValue("http://schemas.android.com/apk/res/com.cca.mobilephone", "bigtitle");
TextView tv_title=(TextView) findViewById(R.id.tv_ui_setting);
//设置文本
tv_title.setText(bigtitle);
}
public SettingCheckView(Context context) {
super(context);
initial(context);
}
private void initial(Context context) {
this.setOrientation(LinearLayout.VERTICAL);
this.addView(View.inflate(context, R.layout.ui_setting_view, null));
set_update=(CheckBox) findViewById(R.id.cb_set_update);
}
/**
* 判断checkbox是否被勾选
*/
public boolean isChecked(){
return set_update.isChecked();
}
/**
* 设置checkbox是否被勾选
*/
public void setChecked(boolean checked){
set_update.setChecked(checked);
}
}
这样一个自定义控件带CheckBox的TextView就定义好了,不过要想正真使用它还需要注意以下内容:
在使用它的布局文件中加入
1、这个控件是没有设置文本的功能的,所以我们要自定义一个设置文本的属性:在使用自定义控件的当前布局文件中先声明属性的命名空间
xmlns:mobilephone="[http://schemas.android.com/apk/res/工程的包名"](http://schemas.android.com/apk/res/com.cca.mobilephone%22)
2、在values定义一个属性文件attrs.xml文件,在里面声明功能
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SettingCheckView">
<attr name="bigtitle" format="string"/>
</declare-styleable>
//或者
<declare-styleable name="SettingCheckView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
3、可以使用自定义控件了
<com.cca.mobilephone.ui.SettingCheckView
android:layout_width="match_parent"
android:layout_height="wrap_content"
mobilephone:bigtitle="我是功能2" />
做到这里就可以使用自定义组合控件了,功能可以设置文本内容,想增加其他的属性,在attrs中定义出来就可以使用了。要是想在另外的布局中使用,只要重新加入命名空间就可以使用了。
网友评论