zoukankan      html  css  js  c++  java
  • Android 使用代码设置selector 的图片或文字颜色

    转自:http://www.jianshu.com/p/06703d56cab8

    通常selector 都是在drawable/color文件夹中定义好,但有时候一些特殊需求需要我们动态通过代码去更改,这个时候就要用到StateListDrawable 和 ColorStateList 了,这两个分别是设置图片和颜色的类

    1、对不同状态的控件设置不同的图片(StateListDrawable)

    通常我们在设置不同状态下图片不同时是这么写的:比如checkBox

    a、定义一个selector文件

    <?xml version= "1.0" encoding="utf-8">

    <selector xmlns:android="http://schemas.android.com/apk/res/android">

               <item android:drawable="@drawable/ic_toolbar_huabuwan_selected"                                 android:state_checked="true"/>

                <item android:drawable="@drawable/ic_toolbar_huabuwan_normal"                                   android:state_checked="false"/>

    </selector>

    b、然后设置给checkBox

    <CheckBox  

     android:layout_height="wrap_content" 

    android:layout_width="wrap_content"  

    android:background="@drawable/selector_check"/>

    这是在图标没有定死的情况下,如果图标是要动态替换则需要通过下面这种方式了

    2、通过代码动态设置图标

    /**

    * 设置底部tab图标

    * @paramradioButton控件

    * @paramdrawableNormal常态时的图片

    * @paramdrawableSelect选中时的图片

    */

    public void setSelectorDrawable(CheckBox cbButton,Drawable drawableNormal,Drawable drawableSelect){

                      StateListDrawable drawable =newStateListDrawable();

                     //选中

                     drawable.addState(new int[]{android.R.attr.state_checked},drawableSelect);

                     //未选中

                     drawable.addState(new int[]{-android.R.attr.state_checked},drawableNormal);

                     cbButton.setBackgroundDrawable(drawable);

    }

    同理selector的颜色也是如此设置,设置颜色的类是ColorStateList

    /**

    * 设置底部tab文字颜色

    * @paramradioButton控件

    * @paramnormal正常时的颜色值

    * @paramchecked选中时的颜色值

    */

    public void setSelectorColor(RadioButton radioButton,intnormal,intchecked){

                  int[] colors =new int[] { normal, checked,normal};

                  int[][] states =new int[3][];

                  states[0] =new int[] { -android.R.attr.state_checked};

                  states[1] =new int[] { android.R.attr.state_checked};

                  states[2] =new int[] {};

                  ColorStateList colorStateList =newColorStateList(states,colors);

                  radioButton.setTextColor(colorStateList);

    }

    注意:-android.R.attr.state_checked 和 android.R.attr.state_checked 的区别在于 “-” 号代表值里的true 和 false ,有“-”为false 没有则为true

  • 相关阅读:
    os.path.join()
    图像旋转后出现黑点
    surging 微服务引擎 1.0 正式发布
    基于docker 如何部署surging分布式微服务引擎
    剥析surging的架构思想
    如何使用thrift 服务引擎组件
    谈谈surging 与多语言混合微服务构思
    surging 社区版本支持.net core 3.1
    surging 微服务引擎 -协议主机的Behavior特性
    谈谈surging 微服务引擎 2.0的链路跟踪和其它新增功能
  • 原文地址:https://www.cnblogs.com/jinglecode/p/6909038.html
Copyright © 2011-2022 走看看