android学习笔记11:按钮

android中的按钮分为两类,普通按钮和图片按钮。而且我们可以通过指定xml文件作为按钮的资源或者背景,来实现按钮的动态变化。下面的这个程序实现了按钮按下去之后按钮的图片改变的效果。

android学习笔记11:按钮android学习笔记11:按钮

按下之前和按下时的对比


这个效果就是通过指定一定xml文件实现的。代码:

<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <!-- 普通文字按钮 --> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/red" android:text="普通按钮" android:textSize="10pt" /> <!-- 普通图片按钮 --> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/blue" android:background="#000000" /> </TableRow> <TableRow> <!-- 按下时显示不同图片的按钮 --> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/button_selector" android:background="#000000" /> <!-- 带文字的图片按钮--> <Button android:id="@+id/test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/button_selector" android:text="带文字的图片按钮" /> </TableRow> </TableLayout>
<?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/red" /> <!-- 指定按钮松开时的图片 --> <item android:state_pressed="false" android:drawable="@drawable/purple" /> </selector>