在 android 中要開啟一個新的視窗 (Activity) 必須透過 Intent 當作一個媒婆。
Intent 物件中除了指定要開啟的視窗外,也可以加入要傳送到新視窗的參數。
下面是一個用來開啟新視窗的按鈕 onClick 事件函式:
public void button_click(View view) {
// 產生 Intent 物件,並指定要開啟的視窗(Activity.class)
Intent intent = new Intent(this, NewActivityName.class);
// 在 Intent 物件中加入要傳送的數值
// putExtra(參數名稱, 參數值)
intent.putExtra("msg", "Hello Activity!");
// 開啟新的視窗
startActivity(intent);
}
在新視窗中可以使用 intent.getStringExtra("msg") 來取得參數。
下面是在新視窗的onStart函式中取得 Intent 參數,並改變視窗中的文字(TextView):
@Override
protected void onStart() {
super.onStart();
// 取得 Intent 並取得名為 msg 的參數值
Intent intent = getIntent();
String message = intent.getStringExtra("msg");
TextView textView = (TextView) findViewById(R.id.message);
textView.setText(message);
}
Intent 中的參數名稱最好使用完整的命名方式,上面為了簡化而採用較直接的方式命名。
請詳閱官方教學:https://developer.android.com/training/basics/firstapp/starting-activity.html
留言
張貼留言