android选择器selector

一、selector概述

selector主要是用来变更控件背景,通过selector不写一行java代码即可实现组件在不同状态下不同的背景颜色或图片的变换。

selector分为:Color-SelectorDrawable-Selector

二、使用selector的步骤

①先写selector的xml文件

②然后在控件的xml文件中设置其颜色或背景属性,使其属性绑定到对应的selector上

三、Color-Selector实例

在res下建个color的文件夹用于存放颜色选择器:res/color/文件名.xml

java中使用:R.color.文件名

xml中使用:@color/文件名

①项目目录结构

②activity_main.xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zgs.colorselector.MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:padding="5dp"
        android:textSize="50sp"
        android:textColor="@color/selector_color_btn_bg"
        android:text="@string/hello_world" />

</RelativeLayout>
③selector_color_btn_bg.xml代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 按下颜色 -->
    <item android:state_pressed="true" android:color="#ff0000"/>
    <!-- 正常颜色 -->
    <item android:color="#00ff00"/>

</selector>
④操作演示,只看按钮中的文字变化,背景变是gif录像软件的问题

四、Drawable-Selector实例

在res下建个drawable的文件夹用于存放图片选择器:res/drawable/文件名.xml

java中使用:R.drawable文件名

xml中使用:@drawable/文件名

①项目目录结构

②activity_main.xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zgs.drawableselector.MainActivity" >

    <Button
        android:padding="20dp"
        android:textSize="30sp"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_btn_bg"
        android:text="@string/hello_world" />

</RelativeLayout>
③selector_btn_bg.xml代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 按下时背景 -->
    <item android:drawable="@drawable/bg1" android:state_pressed="true"/>
    <!-- 正常时背景 -->
    <item android:drawable="@drawable/bg2"/>

</selector>
④操作演示

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值