編輯:進階開發
網頁世界裡要在兩個頁面間跳轉,一個超連結就搞定。手機上呢?最簡單的答案其實是:換掉 Activity 的 Layout。
這個例子準備兩套版面——Layout1(main.xml)與 Layout2(mylayout.xml)。預設顯示 main.xml,裡頭放一顆按鈕,點下去切換到 mylayout.xml;反過來,mylayout.xml 上也有一顆按鈕,點它就能切回 main.xml。以下示範這兩頁如何互相來回。
<?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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="歡迎來到魏祝林的部落格" />
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊進入 Layout2" />
</LinearLayout>
<?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"
android:background="#ffffffff">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome to Mr Wei's blog" />
<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊進入 Layout1" />
</LinearLayout>
setContentViewDemo.java 的做法很直白:每次切換版面就重新呼叫一次 setContentView,然後重新取得按鈕並掛上事件。
package com.android.setContentViewDemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class setContentViewDemo extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 載入 main.xml
setContentView(R.layout.main);
Button bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
goToLayout2();
}
});
}
// 由 main.xml 切換成 mylayout.xml
public void goToLayout2() {
setContentView(R.layout.mylayout);
Button b2 = (Button) findViewById(R.id.bt2);
b2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
goToLayout1();
}
});
}
// 由 mylayout.xml 切換回 main.xml
public void goToLayout1() {
setContentView(R.layout.main);
Button bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
goToLayout2();
}
});
}
}
要留意的是,setContentView 換掉的是「內容檢視」,Activity 本身並沒有被替換,因此所有狀態與變數都還留在同一個 instance 上。這讓它很適合切換同一個功能下的不同視圖;但如果兩頁代表的是真正獨立的職責,該用的是 Intent 開啟另一個 Activity,而不是反覆重設內容檢視。此外,每次切換都會重建整棵檢視樹,頻繁呼叫時版面較複雜就可能感覺到卡頓,那個時候就該考慮改用 ViewStub 或 Fragment 了。
深入 Android 的 Java 進階技術:並發、聯網與資料庫
儘管不少人戲稱「Android 乾脆改名叫 Java GE 好了」,但誰都無法否認,Java 語言是 Android 開發者必備的工具。Android 執行時採用的是自家
從 Windows Mobile 開發者的視角看 Android 開發環境建置
Andrew Koenig 寫過一本現代 C++ 的經典教材《Accelerated C++》。而這麼多年過去,Android 的狀況改善了嗎?它真的還像當年大家口中那樣
Android 原始碼結構(4):external 與 Java 套件該去哪找
Android 的擴充專案收在 external 資料夾中,是一些改寫過、適應 Android 系統的開源專案。有些在主機上執行,有些在目標裝置上執行。因為數量太多就不逐
Android+ARM 組合在 Computex 2009 大放異彩
報告中寫道:「Android 是首款受到強力消費品牌青睞的 Linux 作業系統,而它背後的這隻強力推手,正是 Google。」 報告也坦承,Android 目前仍