介绍
Button继承了TextView,同时还是ImageButton的父类。
Button、ImageButton的功能主要是在UI界面上生成一个按钮,该按钮可以供用户单击,当用户单击时,按钮会触发一个OnClick事件。
Button生成的按钮上显示文字,而ImageButton上则显示图片。即使为ImageButton指定android:text属性也不会在此按钮上显示任何文字。
可以通过android:backgroud为Button添加背景颜色或背景图片;通过android:img为ImageButton指定图片。
用例
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--指定按钮按下时的图片-->
<item android:drawable="@drawable/bg_border" android:state_pressed="true" />
<!--指定按钮松开时的图片-->
<item android:state_pressed="false"
android:drawable="@drawable/leaf"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal">
<TableRow>
<!--普通文字按钮-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_border"
android:text="普通按钮"
android:textSize="10pt"/>
<!--普通图片按钮-->
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaf"
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>
相应地界面展示结果:
摘自《疯狂Android讲义》