編輯:進階開發
先前我們談過幾種可視化與介面導向的編程方法,這次把焦點放在最基礎卻也最容易被低估的元件——Button。看似簡單的按鈕,其實牽涉到版面管理、事件委派與一個很容易踩到的 ID 陷阱。
Android 的介面開發有兩種基本思路。一種是在程式碼中動態 new 出元件,再用 Layout 組合;另一種是以圖形化方式撰寫 XML 布局,編譯成資源後由 Activity 透過 setContentView() 載入,再用 findViewById() 取得各元件的參照來操作。多數人偏好前者,因為最直觀,我們就從這裡說起。
每個介面元件都是 View 的子類,可以單獨佔滿整個螢幕,但真正實用的畫面都是元件的組合。Android 用各種 Layout 來做版面配置,這點和傳統 J2SE 中的 AWT、Swing 相當類似,有底子的人可以直接類比遷移。
回到 Hello World 的經典寫法:
public class HelloActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, World!");
this.setContentView(tv);
}
}
把 TextView 換成 Button 也一樣成立:
super.onCreate(savedInstanceState);
Button btn = new Button(this);
btn.setText("TestButton");
this.setContentView(btn);
執行後你會得到一個佔滿全螢幕的按鈕——顯然不是實用畫面。這時就需要 Layout 出場:
super.onCreate(savedInstanceState);
Button btn = new Button(this);
btn.setText("TestButton");
Button btn2 = new Button(this);
btn2.setText("TestButton2");
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(btn);
layout.addView(btn2);
this.setContentView(layout);
執行後就是兩個上下排列的按鈕了。
怎麼讓按鈕「有用」?如果你寫過 AWT 或手機上的 J2ME,答案大概脫口而出:用 Listener。Android 也沒能免俗,這和 BlackBerry、Symbian 裡的 Observer 是同一個道理,本質上都是觀察者模式。
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class HelloActivity extends Activity implements OnClickListener {
Button btn = null;
Button btn2 = null;
public void onClick(View v) {
if (v == btn) {
this.setTitle("You Clicked Button1");
}
if (v == btn2) {
this.setTitle("You Clicked Button2");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btn = new Button(this);
btn2 = new Button(this);
btn.setText("TestButton1");
btn2.setText("TestButton2");
btn.setOnClickListener(this);
btn2.setOnClickListener(this);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(btn);
layout.addView(btn2);
this.setContentView(layout);
}
}
OnClickListener 介面。onClick()。這是本文最想提醒的一點:不要用 View.getId() 來比對。預設情況下,以程式碼建立的元件 ID 值一律是 -1,除非你手動指定。只有在使用可視化編輯器拉出元件時,系統才會自動為它產生一個 ID。因此與其比對 ID,不如像範例那樣直接比對物件參照,這才是可靠的做法。
Android 2.4 傳聞 4 月登場 代號並非「冰激凌」
有消息指出,Google 準備在 4 月發布下一個 Android 重要版本,而優派(ViewSonic)將搶先推出搭載 Android 2.4 的裝置。 根據小部落格
Android NDK入門:用C/C++擴展應用性能的開發實踐
NDK讓Android開發更靈活 Android NDK允許開發者使用C或C++撰寫部分程式碼,再透過JNI與Java層互動。對於需要高效能運算、遊戲引擎、音訊處理或既有
探索繽紛的Android應用系統:WiFi不掉線與聯盟陣容
隨著Android應用系統問世,廣大Android愛好者总算放下了心裡的期待。作為Google企業策略的一環,它在手機作業系統領域佔有一席之地幾乎是註定的事。 WiFi
Android 手機能力剖析:從 G1 到應用商店的發展軌跡
Google 於 2007 年 11 月 5 日宣布推出 Android,這是一款以 Linux 核心為基礎的手機作業系統。本文回顧它從發布到成熟的歷程,並盤點這個平台在