天天看點

Android 實作【按鈕】 —— 漸變背景色、外邊框顔色、圓角弧度、點選變色 【完整源碼】

實作的效果圖:

圖1:

Android 實作【按鈕】 —— 漸變背景色、外邊框顔色、圓角弧度、點選變色 【完整源碼】

圖2:

Android 實作【按鈕】 —— 漸變背景色、外邊框顔色、圓角弧度、點選變色 【完整源碼】

第一步:

activity_main.xml ,布局代碼

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_marginLeft="100dp"
       android:textColor="#fff"
       android:text="登入"
       android:textSize="18dp"
       android:background="@drawable/button_style"/>

</RelativeLayout>
           

第二步:

在 res/drawble 目錄下建立自定義xml檔案,名字為: button_style.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!--點選之前-->
    <item android:state_pressed="false">
        <shape android:shape="rectangle" >
            <!--設定漸變色 angle=0 從左到右渲染,angle=90從上到下渲染,angle=180 從右到左渲染,-->
            <!--startColor 為開始顔色 ,  endColor 為最終後的顔色-->
            <gradient
                android:angle="0"
                android:startColor="#0626f5"
                android:endColor="#c95669" />
            <!--設定角的弧度-->
            <!--radius 越大,按鈕越圓-->
            <corners android:radius="30dp" />
            <!--設定邊框以及弧度-->
            <!--width 越大邊框越大越明顯  , color 設定外邊框顔色-->
            <stroke
                android:width="3dp"
                android:color="#01f5a8" />
        </shape>
    </item>

    <!--點選之後-->
    <item  android:state_pressed="true">
        <shape>
            <!--點選之後的顔色-->
            <solid android:color="#06f57a"/>
            <!--設定角的弧度-->
            <!--radius 越大,按鈕越圓-->
            <corners android:radius="30dp"/>
            <!--點選之後的邊框-->
            <!--width 越大邊框越大越明顯  , color 設定外邊框顔色-->
            <stroke
                android:width="3dp"
                android:color="#f70307"/>
        </shape>
    </item>
</selector>

           

MainActivity 不用變,直接點選運作即可!

總結:

1.  漸變色
	答: 
	< gradient
    android:angle="0"				    <!--angle=0 從左到右渲染,angle=90從上到下渲染,angle=180 從右到左渲染-->
    android:startColor="#0626f5"		<!--起始顔色-->
    android:endColor="#c95669"   		<!--最終顔色-->
    
2. 弧度
	<corners android:radius="30dp" />	<!--radius 越大,按鈕越圓-->

3. 外邊框
	<stroke
                android:width="3dp"		<!--width 越大邊框越大越明顯 -->
                android:color="#01f5a8" <!--color 設定外邊框顔色 -->

4. 點選變色
     <!--點選之前-->
	 <item android:state_pressed="false">
	 	...
	 	點選之前的按鈕樣式
	 	...
  	 </item>

     <!--點選之後-->
     <item  android:state_pressed="true">
	 	...
	 	點選之後的按鈕樣式
	 	...
  	 </item>