zoukankan      html  css  js  c++  java
  • 使用(Drawable)资源——StateListDrawable资源

          StateListDrawable用于组织多个Drawable对象。当使用StateListDrawable作为目标组件的背景、前景图片时,StateListDrawable对象所显示的Drawable对象会随目标组件状态的改变而自动切换。

          定义StateListDrawable对象的XML文件的根元素为<selector.../>,该元素可以包含多个<item.../>元素,该元素可指定如下属性。

    • android:color或android:drawable:指定颜色或Drawable对象。
    • android:state_xxx:指定一个特定状态。    

         例如如下语法格式:

         

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <!-- 指定特定状态下的颜色 -->
        <item android:state_pressed=["true"|"false"] android:color="hex_color" ></item>
       
    </selector>
    表6.3 StateListDrawable支持的状态
     属性值          含义
     android:state_active  代表是否处于激活状态
     android:state_checkable  代表是否处于可勾选状态
     android:state_checked  代表是否处于可勾选状态
     android:state_endabled  代表是否处于可用状态
     android:state_first  代表是否处于开始状态
     android:state_focused  代表是否处于已得到焦点状态
     android:state_last  代表是否处于结束状态
     android:state_middle  代表是否处于中间状态
     android:state_pressed 代表是否处于已被按下状态 
     android:state_selected  代表是否处于已被选中状态
     android:state_window_focused 代表是否窗口已得到焦点状态 

    实例:高亮显示正在输入的文本框

            前面知道,使用EditText时可指定一个android:textColor属性,该属性用于指定文本框的文字颜色。前面介绍该属性时总是直接给它一个颜色值,因此该文本框的文字颜色总是固定的。借助于StateListDrawable对象,可以让文本框的文字颜色随文本框的状态动态改变。

            为本系统提供如下Drawable资源文件。

           

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <!-- 指定获取焦点时的颜色 -->
        <item android:state_focused="true" android:color="#f44" ></item>
        <!-- 指定失去焦点时的颜色 -->
        <item android:state_focused="false" android:color="#000"></item>
    </selector>

    上面的资源文件中指定了目标组件得到焦点、失去焦点时使用不同的颜色,接下来可以在定义EditText时使用该资源。

      

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    <!-- 使用StateListDrawable资源 -->
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/my_image"/>
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/my_image"/>
    </LinearLayout>

    该应用的Java程序代码不需任何修改,只要显示该界面布局即可。运行该程序将看到如图6.3所示的界面。

     

    通过使用StateListDrawable不仅可以让文本框文字的颜色随文本框状态的改变而切换,也可以让按钮的背景图片随按钮状态的改变而切换。实际上StateListDrawable的功能非常灵活,它可以让各种组件的背景、前景随状态的改变而切换。

  • 相关阅读:
    使用JSON.NET实现对象属性的格式化的自定义
    AspNetCore项目-Service注入或覆盖
    发布Nuget
    收藏
    工具
    快捷键大全
    SqlServer分页查询语句
    面试相关
    Eratosthes algrithm 求素数
    code training
  • 原文地址:https://www.cnblogs.com/wolipengbo/p/3438232.html
Copyright © 2011-2022 走看看