您的位置:首页 > 其它

自定义控件----继承framLayout --textview与checkBox

2017-12-03 19:54 239 查看
//在布局文件中

<com.bwei.administrator.view.zuheView

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/zh"
></com.bwei.administrator.view.zuheView>

//自定义view中

private TextView tv;
private CheckBox ck;

public zuheView(@NonNull Context context) {
super(context);
init();
}

public zuheView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);

init();
}

public zuheView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
//进行初始化数据
private void init() {
//把布局挂载在combineView上
View view=View.inflate(getContext(),R.layout.combine_view,this);
//获取里面的控件
tv = (TextView) view.findViewById(R.id.tvtext);
ck = (CheckBox) view.findViewById(R.id.ck);

//设置点击事件......点击的时候多选框的状态改变
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ck.setChecked(!ck.isChecked());
}
});

}
///对外的两个方法   包括文本的显示   以及checkbox的是否选中
public void setText(String text){
tv.setText(text);
}
//对外提供设置是否选中
public void setChecked(boolean flag){
ck.setChecked(flag);
}

//获取是否选中
public boolean getChecked(){
return ck.isChecked();
}

//在MainActivity中调用设置属性值的方法

    

zuheView = (com.bwei.administrator.view.zuheView) findViewById(R.id.zh);
zuheView.setChecked(true);
zuheView.setText("哩哩啦啦咕咕咕咕");
------------------------------自定义属性值-------------------------------------------
* values下面创建一个attrs.xml文件...attribute
* 添加标签declare_styable自己声明的样式,name自动提示为类名
* 自定义属性attr,,,name为属性名称
* format为数据类型,,,string boolean
* xml声明的时候引用属性
命名空间:xmlns:dash="http://schemas.android.com/apk/res-auto"
* 获取设置的属性
text = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "text");//第一个参数为命名空间,第二个参数为属性名
         checked = attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto", "checked", false);
=======在主布局中============
跟布局
xmlns:yukaihua="http://schemas.android.com/apk/res-auto"
控件中
yukaihua:text="咯咯咯咯咯个"
yukaihua:checked="true"           最终显示的值

自定义view中
定义变量
private String text;
private  boolean checked;
public zuheView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//获取xml里面给的属性值
//第一个参数是命名空间  第二个是属性名
text=attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","text");
checked=attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto","checked",true);
init();
}
在init方法中
//设置初始的值
tv.setText(text);
ck.setChecked(checked);

======values 下的attrs文件========
<declare-styleable name="zuheView">
<attr name="text" format="string"></attr><!--属性名和属性值-->
<attr name="checked" format="boolean"/>
</declare-styleable>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐