Android:Bundle傳遞資料和物件
阿新 • • 發佈:2018-11-14
1、Bundle傳遞資料, 因為Bundle中已經封裝好了簡單資料型別,所以我們直接去設定資料,下面就來看看具體的操作:
case R.id.Btn_Msg:
// 例項化一個Bundle
Bundle bundle = new Bundle();
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
//設定資料
String name="admin" ;String num="123";
//把資料儲存到Bundle裡
bundle.putString("name", name);
bundle.putString("num",num);
//把bundle放入intent裡
intent.putExtra("Message",bundle);
startActivity(intent);
break;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
把資料放到Bundle中,然後仔使用intent去傳遞,下面再來看下怎麼去獲取的從Bundle中傳遞的資料:
//獲取資料
Intent intent = getIntent();
//從intent取出bundle
Bundle bundle = intent.getBundleExtra("Message");
//獲取資料
String name = bundle.getString("name" );
String num = bundle.getString("num");
//顯示資料
text_show.setText(name + "\n" + num);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2、Bundle傳遞物件,如果我們想要傳遞一個複雜的資料型別就會用到Bundle中的方法Serizlizable
在這裡我們要把資料轉成Serizlizable物件,然後在進行相應的操作
如這樣的一個物件:
public class Persion implements Serializable {
private String name;
private String num;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
具體操作如下,這邊把資料設定寫死了,,開始傳遞物件
case R.id.Btn_Obj:
Persion persion=new Persion();
//設定資料
String Name="zhangsan";String Num="111111";
persion.setName(Name);
persion.setNum(Num);
// 例項化一個Bundle
Bundle bundle1 = new Bundle();
// 把Persion資料放入到bundle中
bundle1.putSerializable("persion",persion);
Intent intent1=new Intent(MainActivity.this,Main2Activity.class);
intent1.putExtras(bundle1);
startActivity(intent1);
break;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
同理我也是把物件放到Bundle中,然後在使用Intent進行傳遞,下面看看我們怎麼獲取Bundle傳遞的物件:
Intent intent=getIntent();
// 例項化一個Bundle
Bundle bundle=intent.getExtras();
//獲取裡面的Persion裡面的資料
Persion persion= (Persion) bundle.getSerializable("persion");
text_show.setText("姓名:"+persion.getName()+"\n"+"號碼:"+persion.getNum());
- 1
- 2
- 3
- 4
- 5
- 6
總結一下,在使用Bundle傳遞物件的時候,我先讓Persion類實現Serializable介面,然後用putSerializable(String key,Serializble value)來儲存資料,接收資料的時候再Serializanle getSerizlizble(String key)來取出資料,,道理都很簡單!只是需要一步一步的去解決,,,,做人和寫程式碼一樣,都是需要一步一步腳踏實地的去做,沒有什麼一步登天。。。