Android学习笔记---ImageButton

来源:互联网 发布:淘宝上lol皮肤是真的吗 编辑:程序博客网 时间:2024/04/28 11:39
ImageButton
  1. 用图片显示一个可以被用户按下和单击的按钮。默认情况下,ImageButton看起来和一般的Button没有什么区别。标准的Button将会在状态变化的时候,显示不同的背景颜色。ImageButton表面显示的图片通过XML属性 "android:src"来定义,或者通过setImageResource(int)方法来设置。
  2. 想要去除标准按钮的背景图片,可以通过定义自己的背景图片,或者设置背景为透明。
  3. 如果想要在按钮的不同状态下显示不同的照片,可以通过定义文件"selector.xml"实现。如下例子:
 <?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/button_pressed" /> <!-- pressed -->     <item android:state_focused="true"           android:drawable="@drawable/button_focused" /> <!-- focused -->     <item android:drawable="@drawable/button_normal" /> <!-- default --> </selector>


  •  将这个XML文件保存在你的/res/drawable文件夹下面。程序编译以后,可以通过引用普通的图片资源一样,引用这个XML文件。在你的ImageButton的"android:src"属性中设置后,Android系统会自动按照selector.xml文件中定义的不同图片,在按钮的不同状态下切换图片。
  •  这三种不同状态的图片设置顺序很重要。因为是按照顺序来挨个判断当前状态应该使用哪一个文件。看上面的例子,普通状态是出于最后的。因为一个按钮的正常状态是在这个按钮的前两个状态都不符合的时候的一种状态。

以下是一个例子:

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:layout_width="fill_parent"android:layout_height="wrap_content" android:text="@string/hello" /><ImageButton android:src="@drawable/selector"android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageButton></LinearLayout>


原创粉丝点击