Android 四大元件之 Activity(2)--傳值
阿新 • • 發佈:2019-02-09
Activity 之間的資料傳輸
1. Intent 直接傳值
第一個頁面傳值的方法
第二個頁面取值的方法
2. Intent 傳 Bundle, 由 Bundle 來攜帶 第一個頁面傳值的方法
第二個頁面取值的方法
Intent intent = new Intent();
intent.putExtra("one", num1);
intent.putExtra("str", str);
intent.setClass(FirstActivity.this, SecondActivity.class);
startActivity(intent);
第二個頁面取值的方法
Intent intent = getIntent(); int num = intent.getIntExtra("one", -1); String string = intent.getStringExtra("str");
2. Intent 傳 Bundle, 由 Bundle 來攜帶 第一個頁面傳值的方法
Bundle bundle = new Bundle(); bundle.putString("str", str); bundle.putInt("one", num); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(FirstActivity.this, SecondActivity.class); startActivity(intent);
第二個頁面取值的方法
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("str");
int num = bundle.getInt("one");
3. 用 startActivityForResult() 來跳轉到下一個頁面, 在第二個頁面 setResult(),
然後 finish() ,第一個頁面的 onActivityResult() 接受回撥
例如:頁面A的區域性資訊需要修改時,需要跳到頁面B來修改
頁面A跳轉到頁面B
寫法:頁面B返回跳轉到頁面A 寫法:Intent in=new Intent(); in.setClass(Login.this,Regist.class); startActivityForResult(in, 1);//requestCode(請求編號)這個編號為有那個頁面跳轉回這個頁面的(因為有可能有多個頁面跳轉到這個頁面A)
Intent in=new Intent();
in.setClass(Regist.this, Login.class);
in.putExtra("username", username);
in.putExtra("password", password);
setResult(Activity.RESULT_OK, in);
finish();
頁面A的回撥方法去接收回調的資料
寫法:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
String username=data.getStringExtra("username");
String password=data.getStringExtra("password");
usernameEt.setText(username);
passwordEt.setText(password);
break;
default:
break;
}
}