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

Android 遊戲開發 7:讓 SurfaceView 真正填滿整個螢幕

編輯:Android 遊戲開發

上一節我們成功在 SurfaceView 上放進了 Button 與 TextView,功能上已經通了。但如果你要做的是遊戲,畫面被擠在中間一小塊、像個播放視窗一樣,那顯然不行——我們要的是全屏。

先看問題長什麼樣:

SurfaceView 畫出來的文字被上面那條 Button 區塊硬生生切掉了一截。而且只要畫面上有 Button,就會多出一塊佔位用的長條;就算把 Button 的底色改成白色,也只是讓那條空白變得比較不明顯,遮蔽的問題依然存在。

我們要的效果是這樣:

SurfaceView 撐滿整個可用區域,只有 Button 本身佔據它實際需要的高度,不再多出無用的空白帶。

問題出在版面結構

一開始我以為可以在 XML 裡直接把 Button 放進 SurfaceView 節點內,但這行不通——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 與 Button 是被垂直排列的兄弟節點,LinearLayout 會老老實實地為 Button 保留它那一列的高度,於是 SurfaceView 只能佔剩下的空間,看起來就像被切了一刀。

改用 RelativeLayout 之後,所有子元件預設重疊在同一個堆疊上,SurfaceView 的 fill_parent 就能吃滿整個父容器;Button 透過 layout_alignParentBottom 與 layout_toRightOf 定位在右下角,只佔自己實際的大小,不再排擠別人。TextView 同樣鋪滿整個容器,用 gravity 決定文字對齊位置。

順帶說明外層那個 android:layout_weight="1":它讓 RelativeLayout 在垂直的 LinearLayout 中吃掉所有剩餘高度。如果你打算在這個結構之外再放狀態列或工具列,這個屬性就顯得必要了。

XML 之外的程式碼與上一節完全相同,不需更動。從此之後,你就能在自己的遊戲畫面上自由疊放任何元件了。

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