Android中focusable属性的妙用——底层按钮的实现

本文深入探讨了如何通过设置图片为不可获取焦点,仅使用ImageView组件和简单的XML代码实现按钮按下效果的技巧。通过构建测试工程验证了这一方法的有效性,并详细解释了关键代码的作用。
看到百威啤酒的客户端主界面的按钮,感觉比较新奇,先看下图片:
[img]
http://images.cnblogs.com/cnblogs_com/kofi/201103/201103222037399381.png[/img]

注意图中我画的箭头,当时鼠标点击的黑色圈圈的位置,然后按钮出现了按下的效果(黄色的描边)

刚开始看到这种效果很是好奇,不知道是怎么实现的,后来仔细一想,应该是整个啤酒罐是一张图片(ImageView),该图片是布局在三个按钮之上,然后就是最关键的地方,把图片设置为不可获取焦点,也就是android:focusable="false" ,就这样简单的一行,就可以搞定了!

为了验证我的想法,我建了一个工程来做测试,效果如下图所示:

[img]http://images.cnblogs.com/cnblogs_com/kofi/201103/201103222037469768.png[/img]

具体代码如下:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="button1"
android:background="@drawable/button_selector"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="button2"
android:background="@drawable/button_selector"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="button3"
android:background="@drawable/button_selector"
/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg2"
android:focusable="false"
/>
</RelativeLayout>



button_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<!-- 实心,即填充 -->
<solid android:color="#8470FF"/>
<!-- 描边 -->
<stroke
android:width="2dp"
android:color="#FFFF00"/>
<!-- 圆角 -->
<corners
android:radius="5dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>

<item>
<shape>
<!-- 实心,即填充 -->
<solid android:color="#8470FF"/>
<corners
android:radius="5dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>

关于button_selector.xml中shape的使用有疑问的可以看我上次的文章:Android中shape的使用

ok,就说这么多……
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值