[方法一]從A.class傳到B.class
比喻: 某人要從 A地到B地  靠的是交通工具(Intent )
A.class 目前的Class
B.class 目的Class
| Intent i = newIntent();i.setClass(A.this,B.class)startActivity(i); | 
or
Intent i = new Intent(A.this,B.class);startActivity(i);//開始跳往要去的Activity如果要結束A.class 要加上這行
| A.this.finish();//結束目前Activity | 
[方法二]傳遞資料從A傳到B
比喻: 某人要從 A地帶東西(Bundle)到B地  靠的是交通工具(Intent), 所以他把東西(Bundle) 放在交通工具上(Intent)一起帶去
1.Intent
A.class(傳送資料)
A.class(傳送資料)
B.class(接收資料)
| Intent intent = this.getIntent();//取得傳遞過來的資料   String name = intent.getStringExtra("name");   | 
2.Bundle+Intent
用法簡介:
A.class(傳送資料)
B.class(接收資料)
Bundle bundle = getIntent().getExtras();  String name = bundle.getString("name");double age = bundle.getDouble("age");比喻: 甲拜託乙 從A地到B地買東西回來 ,靠的是交通工具(Intent),
乙回來的話東西送到甲的地址(requestCode/resultCode)
A.class
Intent intent = new Intent(A.this,B.class);//requestCode(識別碼) 型別為 int ,從B傳回來的物件將會有一樣的requestCodestartActivityForResult(intent,requestCode);
B.class
Intent intent = getIntent();Bundle bundle = new Bundle();bundle.putString("name",name);  intent.putExtras(bundle); setResult(requestCode, intent); //requestCode需跟A.class的一樣 B.this.finish();然後要在A.class裡複寫onActivityResult 才能接收B傳回的值
Intent intent = getIntent();@Override     protected void onActivityResult(int requestCode, int resultCode, Intent data) {                  switch(resultCode){//resultCode是剛剛妳A切換到B時設的resultCode          case requestCode://當B傳回來的Intent的requestCode 等於當初A傳出去的話            String result = data.getExtras().getString("name");                         break;                }          }
[方法四]傳遞自定義物件
1.利用Serializable or Parcelable
Bundle.putSerializable(Key,Object);
Bundle.putParcelable(Key, Object);
這兩種都必須時做接口
今天講Serializable
要利用 Serializable 傳遞物件的話
妳的物件必須 implements Serializable
Bundle.putSerializable(Key,Object);
Bundle.putParcelable(Key, Object);
這兩種都必須時做接口
今天講Serializable
要利用 Serializable 傳遞物件的話
妳的物件必須 implements Serializable
public class CustomObject implements Serializable {private static final long serialVersionUID = -7060210544600464481L;//省略以下 為你class的內容}然後在要傳資料的B.class裡CustomObject co_b = new CustomObject ();
Intent i=new Intent();
Bundle bundle=new Bundle();
bundle.putSerializable("CustomObject ", co_b); 
i.putExtras(bundle);
startActivity(i);
在A.class裡
public class A extends Activity{   public static CustomObject co_a = null; //一定要加static 且 public   //以下intent從A到B的內容省略}CustomObject co_b = A.co_a;//直接使用A的static物件
 
3 則留言:
全域變數 延伸閱讀
http://ptodue.blogspot.tw/2015/01/android.html
全域變數 使用singleton pattern實做
https://www.ptt.cc/bbs/AndroidDev/M.1412383579.A.74F.html
參考
http://ptodue.blogspot.tw/2014/12/androidonactivityresult.html
張貼留言