The NoteBook of EricKong

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

首先写一个定义Button样式的XML文件:
新建Android XML文件,类型选Drawable,根结点选selector,文件名就buton_style吧。
程序自动给我们刚刚建的文件里加了selector结点,我们只需要在selector结点里写上三种状态时显示的背景图片(按下、获取焦点,正常)。
代码如下:

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_pressed="true" android:drawable="@drawable/play_press" />
	<item android:state_focused="true" android:drawable="@drawable/play_press" />
	<item android:drawable="@drawable/play" />
</selector>

我这里获取焦点跟点击时显示的是同一张图片,必须严格照上面的顺序写,不可倒。
接下来只要在布局时写Button控件时应用到Button的Background属性即可。

1
2
3
4
<Button android:id="@+id/button1"
	android:layout_width="wrap_content" android:layout_height="wrap_content"
	android:background="@drawable/button_style"
></Button>

最终效果图:

点击时会变。
源代码下载:
Button_style (313)
再加上一种自定义样式方法,上面的是用图片,其实我们可以直接通过定义xml文件来实现不同的样式:
在上面的源代码基础上,只需要修改button_style文件,同样三种状态分开定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_pressed="true">
		<shape>
			<gradient android:startColor="#0d76e1" android:endColor="#0d76e1"
				android:angle="270" />
			<stroke android:width="1dip" android:color="#f403c9" />
			<corners android:radius="2dp" />
			<padding android:left="10dp" android:top="10dp"
				android:right="10dp" android:bottom="10dp" />
		</shape>
	</item>
 
	<item android:state_focused="true">
		<shape>
			<gradient android:startColor="#ffc2b7" android:endColor="#ffc2b7"
				android:angle="270" />
			<stroke android:width="1dip" android:color="#f403c9" />
			<corners android:radius="2dp" />
			<padding android:left="10dp" android:top="10dp"
				android:right="10dp" android:bottom="10dp" />
		</shape>
	</item>
 
	<item>
		<shape>
			<gradient android:startColor="#000000" android:endColor="#ffffff"
				android:angle="180" />
			<stroke android:width="1dip" android:color="#f403c9" />
			<corners android:radius="5dip" />
			<padding android:left="10dp" android:top="10dp"
				android:right="10dp" android:bottom="10dp" />
		</shape>
	</item>
</selector>

gradient 主体渐变 startColor开始颜色,endColor结束颜色 ,angle开始渐变的角度(值只能为90的倍数,0时为左到右渐变,90时为下到上渐变,依次逆时针类推)
stroke 边框 width 边框宽度,color 边框颜色
corners 圆角 radius 半径,0为直角
padding text值的相对位置

posted on 2012-02-27 18:04 Eric_jiang 阅读(22224) 评论(0)  编辑  收藏 所属分类: Android

只有注册用户登录后才能发表评论。


网站导航: