編輯:Android 開發實例
上一篇我們已成功讓 SurfaceView 與 Button、TextView 等元件共存在同一畫面,基本目標算是達成了。但身為遊戲開發者,除非你刻意想要那種「電影銀幕」般的呈現效果(SurfaceView 被夾在中間一小塊),否則絕對不能忍受遊戲畫面只佔螢幕中央一小塊——畫面勢必要全螢幕鋪滿,其他元件只能退居配角。
先來看為什麼需要調整。下圖(圖1)就是問題所在:
(圖1)
看到我們畫出來的文字被硬生生蓋住了吧?只要有 Button,它就會佔去一條長長的區域;就算你去改 Button 布局的顏色,也只是把長條變成白色——好看是好看,但文字一樣被擋住,這可不是我們要的結果。我們真正想要的效果,應該像下圖(圖2)這樣:
(圖2)
對啦,就是這個感覺!View 佔滿整個螢幕,元件本身只在自己該在的位置上覆蓋畫面,不會再多出無用的長條來遮擋內容。
當時我判斷問題出在布局 XML 上。原本想直接在 XML 裡的 SurfaceView 節點下塞進 Button,但 View 裡面不能再放 View,此路不通;於是轉而思考是不是布局的問題。經過多次嘗試,終於調出了正確寫法:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1">
- <com.himi.MySurfaceView android:id="@+id/view3d"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"/>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:text="Himi Button_1"
- android:id="@+id/button1"/>
- <Button android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_toRightOf="@id/button1"
- android:text="Himi Button_2"
- android:id="@+id/button2"/>
- <TextView
- android:id="@+id/textview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:text="This is Himi"
- android:textSize="32sp"
- android:textColor="#00FF00"
- android:gravity="center_horizontal"/>
- </RelativeLayout>
- </LinearLayout>
改動其實不大,主要是把原本的線性布局(LinearLayout)換成相對布局(RelativeLayout)。別看幅度小,為了調對它可是花了大把時間。这样一来,你就能在自己的遊戲 SurfaceView 上隨心所欲地擺放各種元件了。
至於完整源碼,請參考上一篇提供的下載連結,本文只針對 XML 部分做調整,需要的話下載後照著改即可。
自定義 TextView 實現文字倒影效果(附走動時鐘示例)
倒影效果在鎖屏、壁紙、數字時鐘這類場景裡很常見。實現它的關鍵只有一個方法:View 的 getDrawingCache()——先把自身繪製結果取成位圖,再做翻轉和漸變處理
用 ProGuard 混淆程式碼,避免 APK 輕易被反編譯
Android 開發者都得面對一個現實:APK 本質上就是個壓縮檔,反編譯工具隨手可得,自己熬夜寫出來的程式碼,別人幾分鐘就能看得七七八八。 Google 也意識到了這點
Android 開發實作:日曆專案(三)建立樣式與資源
接續日曆專案的進度,這一階段要把視覺資源整理乾淨:顏色、尺寸、Color State List、drawable 與 style 全部抽成獨立檔案。日曆的表格線以 Cel
用 JSONObject 拆解 API 回傳:Android JSON 解析的分層取值邏輯
JSON 這個名稱來自 JavaScript,但它早已脫離該語言,成為一門獨立的資料交換格式,也是 XML 最常被替換的對象。對 Android 開發者而言,理解 JSO