Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 的 XML 樣式技巧:selector、漸層與自訂主題

編輯:初階開發

Android 把樣式抽成 XML 這件事做得很徹底,好處是視覺效果不必動到 Java 程式碼。以下三個技巧——狀態選擇器、漸層背景與自訂主題——幾乎每個專案都會用到。

一、用 selector 處理狀態變化

同一顆按鈕,正常、按下、選中三種狀態各有不同外觀,這件事交給 selector 就好:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"  android:drawable="@drawable/arrow_pressed" />
    <item android:state_checked="true"  android:drawable="@drawable/arrow_pressed" />
    <item                                android:drawable="@drawable/arrow_normal" />
</selector>

寫法上有一個關鍵:把沒有任何條件的項目放在最後。selector 是由上往下比對、命中即停,預設項目若寫在前面,後面的狀態永遠輪不到。

二、用 shape 畫漸層底

不想準備圖片素材時,shape 可以直接畫出漸層方塊:

<shape xmlns:android="https://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <gradient
        android:startColor="#FF0000"   />  <!-- 起始色 -->
        android:endColor="#00FF00"     />  <!-- 結束色 -->
        android:angle="90"             />  <!-- 角度 -->
</shape>

引用方式和一般 drawable 相同:

android:background="@drawable/shape"

angle 只接受 45 的倍數,0 代表由左至右,90 則是由下往上,這點常被誤會成由上往下。

三、自訂主題與視窗標題

想一次調整整個 Activity 的外觀,就寫成 style 再掛成主題:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <!-- 繼承 Android 內建的 Theme.Light -->
    <style name="Theme" parent="android:Theme.Light">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowTitleSize">60dip</item>
        <item name="android:windowTitleStyle">@style/WindowTitle</item>
    </style>

    <style name="WindowTitle" parent="android:WindowTitle">
        <item name="android:singleLine">true</item>
        <item name="android:shadowColor">#BB000000</item>
        <item name="android:shadowRadius">2.75</item>
    </style>
</resources>

要讓某個 Activity 套用這個主題,有兩條路:在 AndroidManifest.xml 的 activity 標籤上加 android:theme="@style/Theme",或是在程式碼裡於 setContentView 之前呼叫:

setTheme(R.style.Theme);

用程式碼設定的話務必注意時機——主題必須在 setContentView() 之前套用,否則視窗已經建立,設定就不會生效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved