在開發Android時,通常都會有好幾個Activity,而要如何傳值也是一門學問。今天就來討論有那些傳值的方式。
第一種方式,直接用Intent物件的pubExtra函式,直接將輸入的值或資料直接帶到另一個Activity。
第二種方式,可以用Bundle物件,組成好幾個資料,再一次帶過去。也可以組成陣列,再用Bundle物件,帶過去。
請在Android Studio 3.x版,新建一個專案。增加一個Empty Activity。再增加一個Activity,選取「Empty Activity」如下圖所示:


在原來的Activity,再拉一個EditText輸入文字元件及一個Button,來呈現出類似這樣的畫面,分別重新改id名稱。如下圖所示:

另一個新增加的Activity,就不用拉任何元件。傳入的值,就用Toast來顯示即可。完整的程式碼如下:
第一個Activity
EditText txt_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt_name = (EditText)findViewById(R.id.txtname);
}
public void prc_change(View v) {
//        //傳值到第二個Activity
//        Intent it = new Intent();
//        it= new Intent(this,Main2Activity.class);
//
//        it.putExtra("pname",txt_name.getText().toString());
//
//        startActivity(it);
//        //傳值到第二個(用Bundle物件)
//        Intent it = new Intent();
//        it= new Intent(this,Main2Activity.class);
//
//        Bundle objbundle = new Bundle();
//        objbundle.putInt("pnumber",123456789);
//        objbundle.putString("pname",txt_name.getText().toString());
//
//        it.putExtras(objbundle);
//        startActivity(it);
        //傳值到第二個(用陣列)
        Intent it = new Intent();
        it= new Intent(this,Main2Activity.class);
        int array[] = {1,2,3};
        Bundle objbundle = new Bundle();
        objbundle.putIntArray("pnumber",array);
        it.putExtras(objbundle);
        startActivity(it);
    }
第二個Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
//        //取得第一個Activity,傳過來的值。
//        Intent it2 = getIntent();
//        prc_showmessage(it2.getStringExtra("pname"));
//        //取得第一個Activity,傳過來的值。(用Bundle物件)
//        Bundle objgetbundle = this.getIntent().getExtras();
//
//        int intnumber = objgetbundle.getInt("pnumber");
//        String strname = objgetbundle.getString("pname");
//
//        prc_showmessage("number:" + String.valueOf(intnumber) + ",name=" + strname);
        //取得第一個Activity,傳過來的值。(用陣列)
        Bundle objgetbundle = this.getIntent().getExtras();
        int[] array = objgetbundle.getIntArray("pnumber");
        prc_showmessage("number:" + String.valueOf(array[0]));
    }
    //顯示訊息
    public void prc_showmessage(String strmessage)
    {
        Toast objtoast = Toast.makeText(this,strmessage, Toast.LENGTH_SHORT);
        objtoast.show();
    }
上述三種方式,直接都寫在程式中。要測試時,請將注解移除,就可以分別測試三個方式。下述為執行出來的結果。
第一種方式,第一個Activity,輸入資料後。在另一個Activity,就會Toast顯示輸入的資料。如下圖示:

第二種方式,第一個Activity,輸入資料後,再跟另一個資料組合成Bundle傳入另一個Activity,就會Toast顯示輸入Bundle物件的值。如下圖示:

第三種方式,第一個Activity,直接將一個一維陣列組成Bundle傳入另一個Activity,就會Toast顯示輸入Bundle物件的陣列的值。如下圖示: