Android 自定义组合控件,属性

22 篇文章 0 订阅
3 篇文章 0 订阅

自定义组合控件

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);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值