$Android自定义控件在不同状态下的属性
2024-10-21 14:25:48
在写代码的时候,有时候需要控件在不同状态下显示不同的外观,比如在按钮按下的时候要变颜色,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"
(三)总结
通过上述方式,其实还可以实现很多种其他的自定义效果,有待进一步探索。
最新文章
- Day6-python基础之模块
- erlang 200w进程测试
- zabbix 3.0快速安装简介(centos 6)
- linux ls -l命令结果含义解析
- 如何用sql批量删除一个id段内的dedecms文章?
- redis web 客户端工具 redis-admin
- Java——线程间通信问题
- arm-linux-gcc 常用参数讲解 gcc编译器使用方法
- Day8 - Python网络编程 Socket编程
- &#39;Invalid update: invalid number of rows in section xx. The number of rows contained in an existing section after the update (xxx)...
- BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式( 二分答案 + 后缀数组 )
- 【十一年】注入框架RoboGuice采用:(Your First Injection into a Custom View class)
- MyBatis 框架笔记
- Nape ";不动";刚体的碰撞交互
- 1572: [Usaco2009 Open]工作安排Job
- MFC中应用对象的成员:窗口指针m_pMainWnd说明
- PowerMockito使用详解
- java字符串替换的问题
- win10切换AHCI模式
- Hystrix 熔断机制