• $Android自定义控件在不同状态下的属性


      在写代码的时候,有时候需要控件在不同状态下显示不同的外观,比如在按钮按下的时候要变颜色,EditText获取焦点时候边框要变颜色等。那么下面就来梳理一下这些是怎么实现的。

      (一)按钮按下时候变颜色

      1、在项目的drawable目录下创建selector_title_imagebutton_bg.xml文件,内容如下:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     3 
     4     <!-- title栏ImageButton按下去时候的颜色 -->
     5     <item android:drawable="@drawable/LightBlue" android:state_pressed="true"/>
     6 
     7     <!-- title栏ImageButton正常时候的颜色 -->
     8     <item android:drawable="@drawable/ThemeDefault"/>
     9 
    10 
    11     <!-- 注:LightBlue和ThemeDefault都是在color.xml文件中定义的drawable类型的颜色值 -->
    12 
    13 </selector>

      2、在values目录下styles.xml文件中增加一个style项,如下:

    1  <!-- 标题栏ImageButton的style -->
    2     <style name="TitleIbStyle" parent="@android:style/Widget.ImageButton">
    3         <item name="android:background">@drawable/selector_title_imagebutton_bg</item>
    4     </style>

      3、在布局xml文件中,创建ImageButton时只需设置其style属性为"TitleIbStyle"即可:

    1       <ImageButton
    2             android:id="@+id/title_base_left_ib"
    3             style="@style/TitleIbStyle"
    4             android:layout_width="wrap_content"
    5             android:layout_height="wrap_content"
    6             android:padding="5dp" />

      

      (二)EditText获取焦点时候边框变颜色

      1、在项目的drawable目录下新建一个selector_edittext_bg.xml文件:

    1 <?xml version="1.0" encoding="utf-8"?>
    2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    3 
    4     <item android:drawable="@drawable/et_pressed" android:state_focused="true"/>
    5     <item android:drawable="@drawable/et_normal"/>
    6     
    7     <!-- 注:et_pressed和et_normal是drawable目录下两张相同大小、填充颜色都为白色但边框颜色不同的圆角矩形的png图片 -->
    8     
    9 </selector>

      2、在values目录下styles.xml文件中增加一个style项,如下:

    1 <!-- EditText的自定义风格 -->
    2     <style name="MyEtStyle" parent="@android:style/Widget.EditText">
    3         <item name="android:background">@drawable/selector_edittext_bg</item>
    4     </style>

      3、在布局xml文件中,创建EditText时只需设置其style属性为"MyEtStyle"即可:

    1           <EditText
    2                     android:id="@+id/content_et"
    3                     style="@style/MyEtStyle"
    4                     android:layout_width="wrap_content"
    5                     android:layout_height="wrap_content"

      

      (三)总结

      通过上述方式,其实还可以实现很多种其他的自定义效果,有待进一步探索。

  • 相关阅读:
    vscode Nodejs 调试 相关总结
    编程语言中的foo,bar到底是什么
    带T和带Z的相关时间是什么 及关于时间的一些知识
    自定义Firefox的 "切换previous标签页"快捷键, 增加"切回last标签页"快捷键
    开始使用Firefox
    Fork-Join 原理深入分析(二)
    Fork-Join分治编程介绍(一)
    Executor框架(七)Future 接口、FutureTask类
    Executor框架(六)CompletionService 接口
    Executor框架(五)Executors工厂类
  • 原文地址:https://www.cnblogs.com/jiayongji/p/5373610.html
Copyright © 2020-2023  润新知