经常用Android编程的人肯定会发现,Android提供的Button和ImageButton控件使得按钮可以带上图片和文字,也就是

(1)Button用android:background属性可以给按钮添加背景图片,android:text属性可以给按钮添加文字。但是有一点很明显的缺陷就是不能改变按钮的背景图片;

(2)ImageButton用android:src属性可以给按钮添加背景图片,android:text属性不能给按钮添加文字。很明显缺陷就是不能给按钮添加文字;

为了解决上面的困扰,所以这篇文章就产生了。

首先,我先贴上代码。

//-------------------main.xml-----------------------

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@drawable/ic_launcher"

android:text="Button" />

android:id="@+id/imageButton1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/ic_launcher" />

android:id="@+id/button2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@layout/selector"

android:text="Button" />

android:id="@+id/imageButton2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@layout/selector" />

//-------------------selector.xml-----------------------

android:drawable="@drawable/other" />

android:drawable="@drawable/ic_launcher" />

这里你会看到原来多了一个元素的缘故。Android中的Selector主要是用来改变ListView和Button控件的默认背景。接下来自然而然就是要详解下。

一、ListView下的selector

(1)ListView下的selector的属性

android:drawable="@drawable/pic1" />

(2)ListView下的selector使用xml文件的方法

1.方法一:在listview中配置android:listSelector="@drawable/xxx

或者在listview的item中添加属性android:background="@drawable/xxx"

2.方法二:Drawable drawable = getResources().getDrawable(R.drawable.xxx);

ListView.setSelector(drawable);但是这样会出现列表有时候为黑的情况,需要加上:android:cacheColorHint="@android:color/transparent"使其透明。

相关属性:

android:state_selected是选中

android:state_focused是获得焦点

android:state_pressed是点击

android:state_enabled是设置是否响应事件,指所有事件

根据这些状态同样可以设置button的selector效果。也可以设置selector改变button中的文字状态。

二、Button下的selector

Button还可以实现更复杂的效果,例如渐变

drawable/selector.xml

//定义当button 处于pressed 状态时的形态。

android:color="#000000" />

android:top="10dp"

android:bottom="10dp"

android:right="10dp"/>

//定义当button获得 focus时的形态

android:color="#333333"/>

android:top="10dp"

android:bottom="10dp"

android:right="10dp"/>

最后,需要在包含 button的xml文件里添加两项。例如main.xml 文件,需要在里加两项

android:focusable="true" android:background="@drawable/selector"

说明:

gradient -- 对应颜色渐变。 startcolor、endcolor就不多说了。 android:angle 是指从哪个角度开始变。

solid -- 填充。

stroke -- 描边。

corners -- 圆角。

padding -- 定义内容离边界的距离。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐