編輯:關於 Android 程式設計
FrameLayout(幀布局)的工作方式很單純:它在屏幕上開闢一個矩形區域,所有放入的子組件預設都會被擺到左上角,並且彼此可以重疊層疊。這個「疊加」特性正是它名字裡「幀」的由來——就像動畫的一格一格畫面疊在一起。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="322dp"
android:src="@drawable/KILL" />
<Button
android:id="@+id/button1"
android:layout_width="240dp"
android:layout_height="107dp"
android:text="Button" />
<TextView
android:id="@+id/textView1"
android:layout_width="154dp"
android:layout_height="62dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</FrameLayout>
效果圖中可以看到:三個子元素全部從左上角 (0, 0) 開始排布,後加入的會蓋在先加入的上面。FrameLayout 中子元素的先後順序決定層疊次序,這一點調試時經常被忽略。
package com.example.framelayout;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout layout = new FrameLayout(this);
// 布局本身佔滿全屏
FrameLayout.LayoutParams rootParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
// 各子元素的尺寸
FrameLayout.LayoutParams imageParams =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 311);
FrameLayout.LayoutParams buttonParams =
new FrameLayout.LayoutParams(281, 173);
FrameLayout.LayoutParams textParams =
new FrameLayout.LayoutParams(183, 85);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.kill);
layout.addView(imageView, imageParams);
Button button = new Button(this);
button.setText("button");
layout.addView(button, buttonParams);
TextView textView = new TextView(this);
textView.setText("TextView");
layout.addView(textView, textParams);
setContentView(layout, rootParams);
}
}
對比兩張運行結果圖,動態代碼與 XML 配置實現的視覺效果完全相同。選擇依據在於場景:
兩者並非互斥,實務上常見的混合做法是:XML 定骨架,代碼填內容。
FrameLayout 真正的用武之地是「疊加」,典型場景有三類:
layout_gravity="bottom|end"。要讓子元素靠對齊而非左上角,記得加 android:layout_gravity,例如 center、bottom|right。這是 FrameLayout 不同於其他容器的一大特性——它支援每個子元素獨立指定重力對齊。
另外,foreground 與 foregroundGravity 屬性可以在整個 FrameLayout 之上再疊一層前景 Drawable,做「列表頂部漸變陰影」這類效果時非常方便。
下節預告:表格布局 TableLayout。
實戰:用 Android Studio 開發與除錯 Android 系統源碼
本文以源碼中 development/tools/idegen/README 作為主要依據,記錄一次完整的實作過程。 環境:Ubuntu 14.10、OpenJDK 1.
安卓應用反編譯(二)-APK 包反編譯實戰解析
第二章 APK 包反編譯 經過編譯器處理後的程式碼與資源,最終會被層層打包成一個 APK 檔案,其中不少內容甚至已被轉換為二進位格式。所幸我們仍有辦法把這些編譯過的產物「
用 ContentObserver 實現 Android 短信驗證碼自動填充
做過註冊登錄流程的人大概都熟悉這個場景:點下「獲取驗證碼」,短信很快進來,可 App 並不會幫你填,你得切到短信介面記住那六位數字,再切回來一個一個敲進輸入框。來回折騰幾
Android 4.4 Framework 剖析:startService 的啟動全流程
我們平常透過 context.startService() 來啟動一個 Service,但這看似簡單的一行呼叫,在 Framework 底層其實經歷了一段漫長的旅程。本文