要從一個 Activity 中呼叫另一個 Activity,
就必須使用 Intent 物件,
而要從一個 Activity 傳值另一個 Activity,
就必須使用 Bundle 物件,
請參考以下範例 (這裡就不列出 Layout XML 檔案內容了) :

來源 Activity 程式碼 :

public class helloWorld extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
            // 設定 Layout 為 main.xml
              setContentView( R.layout.main );
            // 按鈕物件
              Button b1 = (Button)findViewById( R.id.button1 );
            // Button 的 OnClick Trigger
              b1.setOnClickListener(  new OnClickListener(){
         public void onClick(View v) {
                        // 指定要呼叫的 Activity Class
            Intent newAct = new Intent();
            newAct.setClass( helloWorld.this, helloWorld2.class );
                        // 建立 Bundle 物件
            Bundle bData = new Bundle();
                        // 寫入資料到 Bundle 中
            bData.putDouble( "num1", Integer.parseInt(
                                     ((EditText)findViewById( R.id.num1 ))
                                     .getText()
                                     .toString()
                                     ) 
                          );
                        bData.putDouble( "num2", Integer.parseInt(
                                     ((EditText)findViewById( R.id.num2 ))
                                     .getText()
                                     .toString()
                                     )
                           );
                        // 將 Bundle 指定到 Intent
            newAct.putExtras( bData );
                        // 呼叫新的 Activity Class
            startActivity( newAct );
            // 不結束原先的 Activity Class
            // 這樣按返回鍵時, 就可以回到這個 Activity 了
            //helloWorld.this.finish();
        }      
    });
   }
}

 

目的 Activity 程式碼 :

public class helloWorld2 extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
            // 設定 Layout 為 main2.xml      setContentView( R.layout.main2 );
            // 取得 Bundle 物件      Bundle bData = this.getIntent().getExtras();
            // 取得 Bundle 中的資料
            Double num1 = bData.getDouble( "num1" );
            Double num2 = bData.getDouble( "num2" );
            // 顯示結果
          ((TextView)findViewById( R.id.resultText )).setText( num1 + num2 + "" );
   }}

AndroidManifest.xml 要加入第二個 Activity, 不然呼叫時會有問題 :

範例結果 :

 

外部參考:

http://tomkuo139.blogspot.com/2010/01/android-activity-bundle-activity.html

arrow
arrow
    文章標籤
    Android
    全站熱搜

    Frank 發表在 痞客邦 留言(0) 人氣()