Android中focusable屬性的妙用——底層按鈕的實現

看到百威啤酒的客戶端主界面的按鈕,感受比較新奇,先看下圖片:android

bw

注意圖中我畫的箭頭,當時鼠標點擊的黑色圈圈的位置,而後按鈕出現了按下的效果(黃色的描邊)web

剛開始看到這種效果非常好奇,不知道是怎麼實現的,後來仔細一想,應該是整個啤酒罐是一張圖片(ImageView),該圖片是佈局在三個按鈕之上,而後就是最關鍵的地方,把圖片設置爲不可獲取焦點,也就是android:focusable="false" ,就這樣簡單的一行,就能夠搞定了!佈局

爲了驗證個人想法,我建了一個工程來作測試,效果以下圖所示:測試

bw2

具體代碼以下:spa

main.xml:code

<?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:orm

<?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>
相關文章
相關標籤/搜索