android选择器selector

来源:互联网 发布:elasticsearch windows 编辑:程序博客网 时间:2024/05/13 07:10

一、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>
④操作演示

0 0