Android之自定义属性-程序员宅基地

安卓自定义属性主要有3个步骤

  1. 在values文件夹新建attrs.xml文件中声明属性,包括属性名和格式,format常用属性有string ,integer,reference等
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 声明属性集的名称 -->
    <declare-styleable name="MyToggleButtton">
        <!-- 声明属性的name与类型 -->
        <attr name="my_background" format="reference"/>
        <attr name="my_slide_btn" format="reference"/>
        <attr name="curr_state" format="boolean"/>
    </declare-styleable>

</resources>
  1. 在布局文件中使用,使用之前必须先声明命名空间,前面是固定不变的内容,后面是包名.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:zj="http://schemas.android.com/apk/res/com.zj.switchbutton"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <com.zj.switchbutton.MyTrouggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        zj:my_background="@drawable/switch_background"
        zj:my_slide_btn="@drawable/slide_button"
        zj:curr_state="true"
        />

</RelativeLayout>
  1. 在自定义view的构造方法中,通过解析AttributeSet方法,获得所需要的属性值,解析AttributeSet主要有两种方法

第一种:通过attrs.getAttributeValue获得

int counts=attrs.getAttributeCount();
        for(int i=0;i<counts;i++)
        {
            attrs.getAttributeName(i);
            attrs.getAttributeValue(i);
        }


public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        iniView(context);
        String title = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "mytitle");
        desc_on = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "desc_on");
        desc_off = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "desc_off");

        tv_title.setText(title);
        setDesc(desc_off);

    }

第二种:通过TypedArray获得

public MyTrouggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        //获得自定义属性
        TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.MyToggleButtton);
        int N=ta.getIndexCount();
        for(int i=0;i<N;i++)
        {
            int itemId=ta.getIndex(i);
            switch (itemId) {
            case R.styleable.MyToggleButtton_curr_state:
                current_state=ta.getBoolean(itemId, false);

                break;
            case R.styleable.MyToggleButtton_my_background:
                backgroundID=ta.getResourceId(itemId, -1);
                if(backgroundID==-1)
                {
                    throw new RuntimeException("请设置背景图片");
                }
                backgroundBitmap=BitmapFactory.decodeResource(getResources(),backgroundID);
                break;
            case R.styleable.MyToggleButtton_my_slide_btn:
                slideButtonID=ta.getResourceId(itemId, -1);
                if(backgroundID==-1)
                {
                    throw new RuntimeException("请设置图片");
                }
                slideBtnBitmap=BitmapFactory.decodeResource(getResources(), slideButtonID);

            default:
                break;
            }
        }
        init();
    }

自定义属性到底有什么用呢?当界面上的自定义元素有一些值需要改变并且大量重复的时候,自定义属性可以有效的提高代码的重用性,下面是一个简单的例子

声明属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <declare-styleable name="TextView">
        <attr name="mytitle" format="string" />
        <attr name="desc_on" format="string" />
        <attr name="desc_off" format="string" />
    </declare-styleable>
</resources>

在xml文件中定义

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:zj="http://schemas.android.com/apk/res/com.zj.mobilesafe"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="55dip"
        android:background="#8866ff00"
        android:gravity="center"
        android:text="设置中心"
        android:textColor="#000000"
        android:textSize="22sp" />

    <com.zj.mobilesafe.ui.SettingItemView
        android:id="@+id/siv_update"
        android:layout_width="wrap_content"
        android:layout_height="65dip"
        zj:desc_off="设置自动更新已经关闭"
        zj:desc_on="设置自动更新已经开启"
        zj:mytitle="设置自动更新" >
    </com.zj.mobilesafe.ui.SettingItemView>

     <com.zj.mobilesafe.ui.SettingItemView
        android:id="@+id/siv_show_address"
        android:layout_width="wrap_content"
        android:layout_height="65dip"
        zj:desc_off="设置显示号码归属地已经关闭"
        zj:desc_on="设置显示号码归属地已经开启"
        zj:mytitle="设置显示号码归属地" >
    </com.zj.mobilesafe.ui.SettingItemView>

     <com.zj.mobilesafe.ui.SettingClickView
         android:id="@+id/scv_changebg"
         android:layout_width="wrap_content"
        android:layout_height="65dip"
         >

     </com.zj.mobilesafe.ui.SettingClickView>

     <com.zj.mobilesafe.ui.SettingItemView
         android:id="@+id/siv_callsms_safe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        zj:desc_off="黑名单拦截已经关闭"
        zj:desc_on="黑名单拦截已经开启"
        zj:mytitle="黑名单拦截设置" >
    </com.zj.mobilesafe.ui.SettingItemView>

     <com.zj.mobilesafe.ui.SettingItemView
        android:id="@+id/siv_watchdog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        zj:desc_off="看门狗已经关闭"
        zj:desc_on="看门狗已经开启"
        zj:mytitle="程序锁设置" >
    </com.zj.mobilesafe.ui.SettingItemView>


</LinearLayout>

解析属性并且改变属性

/**
 * 自定义的组合控件
 * @author Administrator
 *
 */
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;
    /**
     * 初始化布局文件
     * @param context
     */
    private void iniView(Context context) {
        // TODO Auto-generated method stub
        View.inflate(context, R.layout.setting_item_view, SettingItemView.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, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub

        iniView(context);
    }

    /**
     * 带有两个参数的构造方法,布局文件使用的时候调用 
     * @param context
     * @param attrs
     */

    public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        iniView(context);
        String title = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "mytitle");
        desc_on = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "desc_on");
        desc_off = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.zj.mobilesafe", "desc_off");

        tv_title.setText(title);
        setDesc(desc_off);

    }

    public SettingItemView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

        iniView(context);
    }

    /**
     * 
     * 检验组合和控件是否有焦点
     */

    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);
    }



}

效果如下

这里写图片描述

转载于:https://www.cnblogs.com/jjx2013/p/6223726.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30654583/article/details/97177997

智能推荐

瑞芯微RK3288、RK3399、RK3568、RK3368芯片性能介绍与对比分析_rk3288和rk3568对比-程序员宅基地

文章浏览阅读2.1k次,点赞7次,收藏8次。是瑞芯微推出的一款低功耗、高性能的应用处理器芯片,该芯片基于Big.Little架构,即具有独立的NEON协同处理器的双核Cortex-A72及四核Cortex-A53组合架构,主要应用于计算机、个人互联网移动设备、VR、广告机等智能终端设备。RK3399内置多个高性能硬件处理引擎,能够支持多重格式的视频解码,如:4K*2K@60fps 的H.264/H.265/VP9,也支持1080P@30fps的H.264/MVC/VP8 以及高质量的JPEG编解码和图像的前后处理器。_rk3288和rk3568对比

使用esp 8266物联网开发板 + Mqtt制作远程控制LED小灯_esp8266 mqtt 控制灯亮灭-程序员宅基地

文章浏览阅读1.5k次。如何30快钱以内制作一个手机控制的led小灯_esp8266 mqtt 控制灯亮灭

Ansys Zemax | 如何模拟光学相干层析成像系统_nsdd操作数-程序员宅基地

文章浏览阅读291次,点赞2次,收藏4次。聚焦透镜的坐标(0,20,40),使聚焦透镜与扫描镜保持水平,并保持20mm的距离(该距离在两者的水平位置距离中是任意的),聚焦透镜的材料为N-BK7。_nsdd操作数

流式处理中的文本聚类:探索Apache Beam在文本数据处理中的应用-程序员宅基地

文章浏览阅读5.7k次。作者:禅与计算机程序设计艺术 流式处理中的文本聚类:探索Apache Beam在文本数据处理中的应用引言1.1. 背景介绍随着互联网与物联网的发展,大量的文本数据在各个领

基于微服务架构的分布式系统:如何设计和实现高效的微服务系统_基于微服务的系统-程序员宅基地

文章浏览阅读4.7k次。随着互联网的发展,分布式系统在大型企业应用中越来越普遍。微服务架构作为一种新兴的分布式系统架构,以其灵活性和可扩展性吸引了越来越多的开发者。在微服务架构中,每个服务都是独立的,具有完整的功能和数据职责。本文旨在探讨如何设计和实现高效的微服务系统,以应对现代应用中日益增长的需求。服务注册和发现:服务注册表和反向代理服务。服务路由:服务发现和路由器。服务安全:访问控制、加密和认证。分布式事务:分布式事务工具,如乐观锁。消息队列:异步处理和消息传递。_基于微服务的系统

全网最有效解决centos7 安装MySQL报错No package mysql-server available_no package mod_auth_mysql available.-程序员宅基地

文章浏览阅读856次。今天想在centos7上面装一个mysql,但是无论我yum就还是wget都装不上,提示No package mysql-server…,然后又度娘又各种查资料,试了好多种方法都没有用,最后了解Centos7系统后发现,Centos7带有MariaDB而不是MySQL,MariaDB和MySQL一样也是开元的数据库,同样可以使用yum命令安装,只不过安装使用的并不是老方式的MySQL,而是默认的MariaDB,并且还需要安装的是mariadb-server,如果想继续使用老方式的MySQL,那么需要清_no package mod_auth_mysql available.

随便推点

TensorFlow及其在自然语言处理中的应用_python tensorflow文本理解-程序员宅基地

文章浏览阅读2k次。作者:禅与计算机程序设计艺术 1.简介自然语言处理(Natural Language Processing,NLP)是人工智能领域的一个重要方向。NLP是利用计算机处理及分析文本、语音、图像等各种媒体形式的信息的一门学科。自然语言处理最主要的任务就是把输入的文本进行解析、理解、整合成有意义的信息。可以_python tensorflow文本理解

rocketmq集群安装配置说明-程序员宅基地

文章浏览阅读343次。2019独角兽企业重金招聘Python工程师标准>>> ..._rocketmq 添加集群

构造一个银行账户类(Java)_java定义一个银行账户类,建立账户id为001,姓名张三-程序员宅基地

文章浏览阅读4.4k次。class Bank{ private String name; private float money; public String getName() { return name; } public void setName(String name) { this.name = name; } public float getMoney() { return mone..._java定义一个银行账户类,建立账户id为001,姓名张三

Docker和DockerMachine的对比-程序员宅基地

文章浏览阅读295次,点赞5次,收藏7次。1.背景介绍1. 背景介绍Docker和Docker-Machine都是在容器化技术的基础上发展出来的,它们在软件开发和部署方面发挥了重要作用。Docker是一个开源的应用容器引擎,它使用容器化技术将软件应用与其依赖包装在一起,以便在任何环境中快速部署和运行。Docker-Machine是一个用于管理Docker主机的工具,它可以创建和管理远程Docker主机,以便在不同的环境中运行Doc...

CCF CSP 201703-1 分蛋糕(Java-100分)_ccfcsp分蛋糕-程序员宅基地

文章浏览阅读787次。试题编号: 201703-1试题名称: 分蛋糕时间限制: 1.0s内存限制: 256.0MB问题描述: 问题描述  小明今天生日,他有n块蛋糕要分给朋友们吃,这n块蛋糕(编号为1到n)的重量分别为a1, a2, …, an。小明想分给每个朋友至少重量为k的蛋糕。小明的朋友们已经排好队准备领蛋糕,对于每个朋友,小明总是先将自己手中编号最小的蛋糕分_ccfcsp分蛋糕

前端访问性:实现可访问性与易用性-程序员宅基地

文章浏览阅读902次,点赞22次,收藏14次。1.背景介绍前端访问性是一种设计理念,它关注于为所有用户提供相同或类似的体验,无论他们的能力、年龄、技能水平或其他因素。可访问性和易用性是前端访问性的关键组成部分,它们确保了网站或应用程序对所有用户都是友好的。在过去的几年里,前端访问性变得越来越重要,因为互联网已经成为了人们生活和工作的重要组成部分。因此,确保所有用户都能够轻松地使用网站或应用程序变得至关重要。在本文中,我们将讨论前端...

推荐文章

热门文章

相关标签