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

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

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

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

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

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

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

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

  

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

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

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

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

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

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

           <EditText
android:id="@+id/content_et"
style="@style/MyEtStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

  

  (三)总结

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

最新文章

  1. Day6-python基础之模块
  2. erlang 200w进程测试
  3. zabbix 3.0快速安装简介(centos 6)
  4. linux ls -l命令结果含义解析
  5. 如何用sql批量删除一个id段内的dedecms文章?
  6. redis web 客户端工具 redis-admin
  7. Java——线程间通信问题
  8. arm-linux-gcc 常用参数讲解 gcc编译器使用方法
  9. Day8 - Python网络编程 Socket编程
  10. &#39;Invalid update: invalid number of rows in section xx. The number of rows contained in an existing section after the update (xxx)...
  11. BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式( 二分答案 + 后缀数组 )
  12. 【十一年】注入框架RoboGuice采用:(Your First Injection into a Custom View class)
  13. MyBatis 框架笔记
  14. Nape &quot;不动&quot;刚体的碰撞交互
  15. 1572: [Usaco2009 Open]工作安排Job
  16. MFC中应用对象的成员:窗口指针m_pMainWnd说明
  17. PowerMockito使用详解
  18. java字符串替换的问题
  19. win10切换AHCI模式
  20. Hystrix 熔断机制

热门文章

  1. ASP.NET MVC 表单提交多层子级实体集合数据到控制器中
  2. Customize Netbeans Platform Splash Screen and About Dialog
  3. python3----字符串中的字符倒转
  4. 加载Chrome&Firefox配置
  5. TensorFlow实战:Chapter-4(CNN-2-经典卷积神经网络(AlexNet、VGGNet))
  6. 用js判断页面是否加载完成
  7. Wedding (poj 3648 2-SAT 输出随意一组解)
  8. HDU4781(2013成都站A题)
  9. Linux 进程(二):进程关系及其守护进程
  10. Highway