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

Android 開發常用技巧整理:Drawable、螢幕尺寸與 Style

編輯:進階開發

在模擬器與真機上反覆實作,是累積 Android 開發經驗最有效的方式。本文整理三個高頻出現的實務技巧,都是小型專案裡幾乎一定會用到的基礎操作。

一、Drawable 的使用

Android 中最常處理的資源類型之一就是 Drawable,它提供一組通用 API 來代表各種視覺資源,可以是色值、漸層、點陣圖或 Shape。說得白一點,就是從 res 底下把資源取出來套用到元件上。

例如先把顏色定義在 values/color.xml:

<?XML version="1.0" encoding="utf-8" ?>
<resources>
    <drawable name="darkgray">#808080FF</drawable>
    <drawable name="white">#FFFFFFFF</drawable>
</resources>

接著在程式碼中取出並設為文字方塊的背景色:

Resources resources = getBaseContext().getResources();
Drawable HippoDrawable = resources.getDrawable(R.drawable.white);
mTextVIEW01.setBackgroundDrawable(HippoDrawable);

同樣的資源也可以用來設定文字顏色,寫法一樣是透過 getDrawable() 取得後套用。

二、取得螢幕實際尺寸

需要依螢幕寬高做版面計算或自繪時,用 DisplayMetrics 取得像素數值最直接:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;

要注意這裡取得的是像素(px),若要做跨裝置一致的排版,記得搭配 dm.densityDpi 換算成 dp 或 sp 再使用。

三、用 Style 機制統一元件樣式

只加一行 style 屬性,就能改寫元件的呈現效果,這是 Android Style 機制最方便的地方。先在 values/styles.xml 定義:

<?XML version="1.0" encoding="utf-8" ?>
<resources>
    <style name="DavidStyleText1">
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">#EC9237</item>
    </style>
    <style name="DavidStyleText2">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">#FF7F7C</item>
        <item name="android:fromAlpha">0.0</item>
        <item name="android:toAlpha">0.0</item>
    </style>
</resources>

然後在版面檔中直接引用,兩個 TextView 就能各自套用不同樣式:

<?XML version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="@drawable/white"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- 套用樣式一 -->
    <TextView style="@style/DavidStyleText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:text="@string/str_text_view1" />

    <!-- 套用樣式二 -->
    <TextView style="@style/DavidStyleText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:text="@string/str_text_view2" />
</LinearLayout>

把重複的屬性抽成 Style 之後,版面檔會乾淨很多,要調整全站的文字風格時也只需改一處,這在專案規模變大後尤其明顯。

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