Android中focusable屬性的妙用之底層按鈕的實(shí)現(xiàn)
在Android中使用focusable 屬性來實(shí)現(xiàn)按鈕的特效,看到百威啤酒的客戶端主界面的按鈕,感覺比較新奇,先看下圖片:
注意圖中我畫的箭頭,當(dāng)時(shí)鼠標(biāo)點(diǎn)擊的黑色圈圈的位置,然后按鈕出現(xiàn)了按下的效果(黃色的描邊)
剛開始看到這種效果很是好奇,不知道是怎么實(shí)現(xiàn)的,后來仔細(xì)一想,應(yīng)該是整個(gè)啤酒罐是一張圖片(ImageView),該圖片是布局在三個(gè)按鈕之上,然后就是最關(guān)鍵的地方,把圖片設(shè)置為不可獲取焦點(diǎn),也就是android:focusable="false" ,就這樣簡單的一行,就可以搞定了!
為了驗(yàn)證我的想法,我建了一個(gè)工程來做測試,效果如下圖所示:
具體代碼如下:
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>
- <!-- 實(shí)心,即填充 -->
- <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>
- <!-- 實(shí)心,即填充 -->
- <solid android:color="#8470FF"/>
- <corners
- android:radius="5dp" />
- <padding
- android:left="10dp"
- android:top="10dp"
- android:right="10dp"
- android:bottom="10dp" />
- </shape>
- </item>
- </selector>
關(guān)于button_selector.xml中shape的使用有疑問的可以看我上次的文章:Android中shape的使用。
【編輯推薦】