Android学习笔记---ImageButton


ImageButton
  1. 用图片显示一个可以被用户按下和单击的按钮。默认情况下,ImageButton看起来和一般的Button没有什么区别。标准的Button将会在状态变化的时候,显示不同的背景颜色。ImageButton表面显示的图片通过XML属性 "Android:src"来定义,或者通过setImageResource(int)方法来设置。
  2. 想要去除标准按钮的背景图片,可以通过定义自己的背景图片,或者设置背景为透明。
  3. 如果想要在按钮的不同状态下显示不同的照片,可以通过定义文件"selector.xml"实现。如下例子:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_pressed="true"  
  4.           android:drawable="@drawable/button_pressed" /> <!-- pressed -->  
  5.     <item android:state_focused="true"  
  6.           android:drawable="@drawable/button_focused" /> <!-- focused -->  
  7.     <item android:drawable="@drawable/button_normal" /> <!-- default -->  
  8. </selector>  
  •  将这个XML文件保存在你的/res/drawable文件夹下面。程序编译以后,可以通过引用普通的图片资源一样,引用这个XML文件。在你的ImageButton的"android:src"属性中设置后,Android系统会自动按照selector.xml文件中定义的不同图片,在按钮的不同状态下切换图片。
  •  这三种不同状态的图片设置顺序很重要。因为是按照顺序来挨个判断当前状态应该使用哪一个文件。看上面的例子,普通状态是出于最后的。因为一个按钮的正常状态是在这个按钮的前两个状态都不符合的时候的一种状态。

以下是一个例子:

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <TextView android:layout_width="fill_parent"  
  6.         android:layout_height="wrap_content" android:text="@string/hello" />  
  7.     <ImageButton android:src="@drawable/selector"  
  8.         android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageButton>  
  9. </LinearLayout><strong>  
  10. </strong>  

相关内容