Android自定义组合控件

一般的步骤:

1.      定义一个xml布局文件,这个布局文件中的内容是:

你想要自定义的控件的所有组件,分开来写

2. 定义一个java类,继承你想定义的内容,比如继承RelativeLayout

3.  在activity的xml中,使用java类中自定义的控件

 

接下来举例:

 目标如下:


点击设置是否自动更新,checkbox也会被选中,因此需要将,2个textview,checkbox设置为一个组合控件。


第一步:

定义一个RalativeLayout,实现



第二步:

创建一个Java类,继承RelativeLayout,并在java类中加载第一步实现的布局文件

package com.android.programmer_C.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.programmer_pc.mobilesafe.R;

/**
 * Created by Programmer_PC on 2016/6/27.
 */
public class SettingItemView extends RelativeLayout {
    private CheckBox cb_status;
    private TextView tv_desc;
    private TextView tv_title;

    private  String desc_on;
    private String desc_off;

    private void iniView(Context context){
        //把一个布局文件---》View 并且加载在SettingItemView
        View.inflate(context, R.layout.setting_item_view, this);
        cb_status = (CheckBox) this.findViewById(R.id.cb_status);
        tv_desc = (TextView) this.findViewById(R.id.tv_desc);
        tv_title = (TextView) this.findViewById(R.id.tv_title);
    }

    public SettingItemView(Context context) {
        super(context);
    }

    public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        iniView(context);
    }

    public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    /**
     * 校验组合控件是否选中
     */

    public boolean isChecked(){
        return cb_status.isChecked();
    }

    /**
     * 设置组合控件的状态
     */

    public void setChecked(boolean checked){
        if(checked){
            setDesc(desc_on);
        }else{
            setDesc(desc_off);
        }
        cb_status.setChecked(checked);
    }

    /**
     * 设置 组合控件的描述信息
     */

    public void setDesc(String text){
        tv_desc.setText(text);
    }
}

第三步:直接使用上述定义的组合控件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值