Jollen's email: jollen # jollen.org

more: Jollen's Consulting | Jollen's Wiki

« 清華大學Android種子教學培訓課程: Day1 上課紀錄 | Home | 走入雲端的開發套件 »

Jollen 的 Android 教學,#31: R.drawable 應用-如何使用NinePatch圖檔

jollen 發表於 September 20, 2009 10:39 PM

上一篇日記介紹了「如何製作NinePatch圖檔」,因此有讀者問到「如何寫程式」,因此特別補上這篇教學。

開始寫程式: HelloNinePatch

範例HelloNinePatch的實作方式如下。

Step 1. 建立一個新的Android專案,命名為HelloNinePatch。

Step 2. 將arrow.9.png托曳(drag)到HelloNinePatch專案裡的「res/drawable」目錄下。如圖1。

ninepatch-res-1.png
圖1: 將arrow.9.png放進res/drawable資料夾

Step 3. 修改UI(res/layout/main.xml),設計出上一篇教學(#30)裡的圖2畫面。main.xml的內容如下。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="small world"
    android:textSize="12sp"
    android:background="@drawable/arrow"
    />
<Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="big world"
    android:textSize="24sp"
    android:background="@drawable/arrow"
    />
<Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="super world"
    android:textSize="48sp"
    android:background="@drawable/arrow"
    />
</LinearLayout>

這裡的做法是,在UI上擺放Button元件,並設定Button上的文字及大小。透過「android:background」屬性的設定,我們將Button的背景設定為「@drawable/arrow」,即「drawable資源(drawable/目錄下)裡的arrow圖檔」,Android框架會去找到arrow.9.png檔案。

因為arrow.9.png是一張NinePatch圖檔,因此會隨著Button上的文字大小延展。

Step 4: 完成HellNinePatch

程式碼不需要做任何修改,直接執行HelloNinePatch專案即可。

--jollen

引用通告

如果您想引用這篇文章到您的Blog,
請複製下面的鏈接,並放置到您發表文章的相應界面中。

http://www.jollen.org/cgi-bin/mt3/mt-tb.cgi/674

發表一個評論

(您發表的意見將被立即接受,但需要一點時間與後端伺服器做同步,您的留言才會顯示在網站上。為避免 spam 攻撃,按「發表」後請輸入帳號密碼。使用者帳號:「nospam」、密碼:「nospam」。)

[Top] Copyright (C) 2006,2010 www.jollen.org.
All rights reserved. All content licensed under Creative Commons License.