【android開發筆記】為Button的背景圖片添加邊框式樣式效果


現在做的項目遇到一個問題,設計給過來的圖片只有一種狀態,但是實現的需求是要求有兩個狀態,另一種選狀態為圖片背景加邊框。如圖:

剛開使用使用ImageView ,ImageViewButton 效果不是很明顯;

 

后來發現 layer-list 能很好的實現這個效果,先分別建 正常模式與選中模式的xml文件:

正常模式:btn_angle_normal_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/transparent_half" />
    <stroke
        android:width="@dimen/dimen_6px"
        android:color="@color/transparent_half" />
    <padding
        android:bottom="0.0dip"
        android:left="0.0dip"
        android:right="0.0dip"
        android:top="0.0dip" />
</shape>
選中模式:btn_angle_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/transparent_half" />
    <stroke
        android:width="@dimen/dimen_6px"
        android:color="@color/gold" />
    <padding
        android:bottom="0.0dip"
        android:left="0.0dip"
        android:right="0.0dip"
        android:top="0.0dip" />
</shape>

 

Selector :common_recangle_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn_angle_bg" android:state_pressed="true" />
    <item android:drawable="@drawable/btn_angle_bg" android:state_selected="true" />
    <item android:drawable="@drawable/btn_angle_normal_bg" android:state_enabled="true" />
</selector>

 

Layer-list文件:zhuang_btn.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/common_recangle_bg" /> //這里是normal與press的xml文件
<item
    android:bottom="@dimen/dimen_4px"
    android:drawable="@mipmap/bai_table_zhuang_up" //這里是背景圖片
    android:left="@dimen/dimen_4px"
    android:right="@dimen/dimen_4px"
    android:top="@dimen/dimen_4px" />
</layer-list>

 

然后在布局里的內部控件使用:

 <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/zhuang_btn"
            android:gravity="bottom|center"
            android:text="4545\n"
            android:textSize="@dimen/dimen_tv_20" />

 

基本這樣可以實現了這個效果!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM