Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 資源檔常用手法整理:shape、selector、arrays 與 Notification

編輯:關於 Android 程式設計

開發中反覆查到、卻又老是記不清的資源檔寫法,值得整理成一份備忘。以下收錄幾個高頻項目。

arrays.xml 定義陣列

<resources>
    <!-- share items -->
    <string-array name="app_share_items">
        <item>新浪微博</item>
        <item>騰訊微博</item>
    </string-array>
</resources>

純色圓角背景

<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#4a90e2" />
    <corners android:radius="95dp" />
</shape>

用法:

android:background="@drawable/xml_background_button_blue"

取得這種背景後,實際型別是 Drawable.GradientDrawable,因此可以在程式碼中動態改色而保留原本的圓角設定,不必重新建立 Drawable。

顏色表示法

Android 的顏色格式是 ARGB,alpha 範圍 0(全透明)到 255(全不透明)。寫成四位數的 #8f0f 這類簡寫也支援,可視為 pink 的縮寫形式。實務上建議統一在 colors.xml 命名管理,避免同一個色值散落在各處。

浮動視窗權限

要在其他應用之上彈視窗,Manifest 裡需加上:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

注意這個權限在較新版本中需要引導使用者到設定頁手動開啟,單純宣告並不足夠。

資源檔與類別的對應關係

這張對照表最容易搞混,記住就不會再翻錯文件:

selector 對應 StateListDrawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/xml_login_button_press"/>
    <item android:drawable="@drawable/xml_login_button_normal"/>
</selector>

也可以讓每個狀態各自帶一個 shape:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/pressed_color"/>
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="@color/transparent"/>
        </shape>
    </item>
</selector>

shape 對應 GradientDrawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#4a90e2" />
    <corners android:radius="95dp" />
</shape>

Notification 的兩個眉角

1. Action 與 Activity 的綁定,兩步缺一不可

先定義一個 Action 常數:

public static final String DOWNLOAD_MANAGER = "com.james.app.download";

再在對應的 Activity 中補上 IntentFilter:

<intent-filter>
    <action android:name="com.james.app.download"/>
    <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

2. Notification 是靠 Action 區分,不是靠 ID

這一點常被誤解。許多人以為換個 notify ID 就能更新不同通知,實際上系統判斷「是不是同一則通知」看的是 Action,ID 只是次要線索。想做多則獨立通知,請給每一則不同的 Action。

延伸閱讀:《Android 資源操作技巧匯總》《Android 開發入門與進階教程》《Android 控件用法總結》《Android 短信與電話操作技巧匯總》《Android 多媒體操作技巧匯總》。

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