使用Intent在不同activity間進行傳參的兩種方法
- 使用Intent的putExtra()方法進行參數傳遞
傳遞參數
Intent intent = new Intent(FromActivity.this, ToActivity.class);
/*設置inent的傳遞參數*/
intent.putExtra("args", args);
startActivity(intent);
接收參數
// 接收傳入的intent對象
Intent intent = getIntent();
if(intent != null){
//獲取intent中的參數
String regAccount = intent.getStringExtra("args");
}
- 使用Bundle對象將參數封裝進行傳遞
封裝并傳遞參數
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
// 使用Bundle對象進行傳參,做一層封裝
Bundle bundle = new Bundle();
bundle.putString("accountName",accountName);
bundle.putInt("accountAge",accountAge);
// intent對象綁定bundle對象
intent.putExtras(bundle);
startActivity(intent);
接收參數
// 接受傳入的intent對象
Intent intent = getIntent();
if(intent != null){
// 獲取Bundle對象中的參數
Bundle bundle = intent.getExtras();
if(bundle != null){
String accountName = bundle.getString("accountName", "");
Int accountAge = bundle.getInt("accountAge", 1);
}