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

【Android 遊戲開發之七】打造全螢幕遊戲畫面:再探 SurfaceView 中排列元件的正確布局方案

編輯:Android 開發實例

上一篇我們已成功讓 SurfaceView 與 Button、TextView 等元件共存在同一畫面,基本目標算是達成了。但身為遊戲開發者,除非你刻意想要那種「電影銀幕」般的呈現效果(SurfaceView 被夾在中間一小塊),否則絕對不能忍受遊戲畫面只佔螢幕中央一小塊——畫面勢必要全螢幕鋪滿,其他元件只能退居配角。

先來看為什麼需要調整。下圖(圖1)就是問題所在:

(圖1)

看到我們畫出來的文字被硬生生蓋住了吧?只要有 Button,它就會佔去一條長長的區域;就算你去改 Button 布局的顏色,也只是把長條變成白色——好看是好看,但文字一樣被擋住,這可不是我們要的結果。我們真正想要的效果,應該像下圖(圖2)這樣:

(圖2)

對啦,就是這個感覺!View 佔滿整個螢幕,元件本身只在自己該在的位置上覆蓋畫面,不會再多出無用的長條來遮擋內容。

當時我判斷問題出在布局 XML 上。原本想直接在 XML 裡的 SurfaceView 節點下塞進 Button,但 View 裡面不能再放 View,此路不通;於是轉而思考是不是布局的問題。經過多次嘗試,終於調出了正確寫法:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent">
  6.     <RelativeLayout
  7.         android:layout_width="fill_parent"
  8.         android:layout_height="wrap_content"
  9.         android:layout_weight="1">
  10.     <com.himi.MySurfaceView android:id="@+id/view3d"
  11.         android:layout_width="fill_parent"
  12.         android:layout_height="fill_parent"/>
  13.     <Button
  14.         android:layout_width="wrap_content"
  15.         android:layout_height="wrap_content"
  16.         android:layout_alignParentBottom="true"
  17.         android:text="Himi Button_1"
  18.         android:id="@+id/button1"/>
  19.     <Button android:layout_width="wrap_content"
  20.         android:layout_height="wrap_content"
  21.         android:layout_alignParentBottom="true"
  22.         android:layout_toRightOf="@id/button1"
  23.         android:text="Himi Button_2"
  24.         android:id="@+id/button2"/>
  25.     <TextView
  26.         android:id="@+id/textview"
  27.         android:layout_width="fill_parent"
  28.         android:layout_height="fill_parent"
  29.         android:text="This is Himi"
  30.         android:textSize="32sp"
  31.         android:textColor="#00FF00"
  32.         android:gravity="center_horizontal"/>
  33.     </RelativeLayout>
  34. </LinearLayout>

改動其實不大,主要是把原本的線性布局(LinearLayout)換成相對布局(RelativeLayout)。別看幅度小,為了調對它可是花了大把時間。这样一来,你就能在自己的遊戲 SurfaceView 上隨心所欲地擺放各種元件了。

至於完整源碼,請參考上一篇提供的下載連結,本文只針對 XML 部分做調整,需要的話下載後照著改即可。

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