【Android基础】ImageButton运用
在ANDROID程序中,会使用大量的ImageButton控件。ImageButton相对于Button来讲具有更加良好的外观和交互表现力,所以如何在程序中体现其交互优势显得尤为重要。
一般在<imagebutton>标签中配置android:src属性,设置为drawable/下具体图片文件即可。
但我更建议使用android:background标签,这样有两个方便之处:
1、没有系统默认的按钮背景,完全展示图片。
2、不用调整图片大小,图片能自适应按钮大小。
为了展现更好的交互效果,比如按下按钮会展示有按下效果的图片,以达到更好的交互性,我们就需要做一些额外的工作了。
首先,在res/drawable下新建一个名为advancedbutton.xml的selector配置文件,如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/onfocusimage"></item>
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/clickimage"></item>
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/clickimage"></item>
<item android:drawable="@drawable/defaultimage"></item>
</selector>
上述XML文件制定了一系列的动作以及该动作对应显示的图片。常见的动作就是:获取/失去焦点、点击按钮。 配置好advancedbutton文件后,在ImageButton中指定android:background值后便大功告成了。
<imagebutton>
android:id="@+id/image_Button"
android:layout_width="50dip"
android:layout_height="50dip"
android:background="@drawable/advancedbutton" >
</imagebutton>
PS:ANDROID中控件大小建议使用dip而非px。因为像素点因各种屏幕分辨率不一样会被渲染得和预期不一致。而dip适合硬件相关,会有更好的屏幕适应效果。