編輯:關於 Android 程式設計
Activity 之間的跳轉是 Android 最基礎的操作,透過 Intent 完成。本文以「按按鈕跳到另一個 Activity 並帶值過去」為例,走一遍完整流程。
選擇 File → New → Android Application,依序填入應用名稱、專案名稱與套件名稱。建立完成後,在 src/com.example.helloworld 下可找到 MainActivity.java。
先在 res/layout/activity_main.xml 的圖形編輯器中拖入一個 Button,系統會自動產生對應的 XML。請記下它的 id(本例為 button1),後續程式碼要用。
package com.example.helloworld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.button = (Button) this.findViewById(R.id.button1);
this.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, IntentActivity.class);
intent.putExtra("name", "Hello World");
startActivity(intent);
}
});
}
}
這裡的關鍵是 Intent:setClass() 明確指定要前往的目標元件,putExtra() 放入要傳遞的資料(key-value 形式),最後 startActivity() 啟動它。
1. 右鍵點擊 src/com.example.helloworld,選擇 New → Class,名稱填 IntentActivity(不需加 .java)。
2. 在 res/layout 右鍵選擇 New → Android XML File,建立 activity_intent.xml,並拖入一個 TextView。
3. 在 AndroidManifest.xml 中註冊這個 Activity,這一步最容易被遺漏,漏了會在執行時丟出 ActivityNotFoundException:
<activity
android:name="com.example.helloworld.IntentActivity">
</activity>
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class IntentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent);
Intent intent = getIntent();
String string = intent.getStringExtra("name");
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(string);
setContentView(textView);
}
}
getIntent() 取得啟動自己的 Intent,再用 getStringExtra("name") 依 key 取出值。這裡的 key 字串必須與送出端 putExtra 時使用的完全一致。
啟動模擬器或接上實機,執行專案,按下按鈕後就會跳到新畫面並顯示傳遞的文字。
顯性 Intent(setClass/new Intent(ctx, Xxx.class))用於已知的內部元件;隱性 Intent(只指定 action)則由系統找出能處理的元件,例如 ACTION_VIEW 開啟網址、ACTION_SEND 分享文字。
傳值除了 Bundle 式的 putExtra,也可以實作 Serializable 或 Parcelable 介面來傳遞自訂物件;Parcelable 是 Android 效能較佳的建議做法。若只需要回傳結果給上一頁,則改用 startActivityForResult() 搭配 setResult(),並在 onActivityResult() 中接收。
切換畫面時若要加上轉場動畫,可在 startActivity() 之後呼叫 overridePendingTransition(enterAnim, exitAnim)。
Android 界面編程:導航欄與菜單(六)
2.7 導航欄與菜單 2.7.1 ActionBar ActionBar 是 Android 3.0(API 11)起加入的新特性,位於 Activity 視窗的頂部,
在 Ubuntu 上搭建 Android 開發環境(Android Studio)實錄
假期沒事,裝了最新的 Ubuntu 16.04,順手把 Android 開發環境也搬過來體驗一下。整個過程不算太順,踩了幾個坑,記錄下來給要走同一條路的人參考。 一、下
ExpandableListView 可折疊列表與 StackView 棧式視圖用法詳解
這一節介紹兩個帶適配器的控件:ExpandableListView(可折疊列表)與 StackView(棧式視圖)。前者是 QQ 好友分組那類效果的經典實現,後者則能把一
Android 應用程式自動更新的實作流程
應用程式上線後,通常需要提供更新機制。常見做法是讓應用程式連線到伺服器取得版本資訊,判斷是否有新版本,若有則下載 APK 並引導安裝。 效果如下: 版本資訊來源 伺