Android(安卓)四大组件之 Activity(2)--传值
16lz
2021-12-04
Activity 之间的数据传输
1. Intent 直接传值
第一个页面传值的方法
第二个页面取值的方法
2. Intent 传 Bundle, 由 Bundle 来携带
第一个页面传值的方法
第二个页面取值的方法
3. 用 startActivityForResult() 来跳转到下一个页面, 在第二个页面 setResult(), 然后 finish() ,第一个页面的 onActivityResult() 接受回调
例如:页面A的局部信息需要修改时,需要跳到页面B来修改
页面A跳转到页面B 写法:
页面B返回跳转到页面A 写法:
页面A的回调方法去接收回调的数据 写法:
1. Intent 直接传值
第一个页面传值的方法
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 写法:
Intent in=new Intent(); in.setClass(Login.this,Regist.class); startActivityForResult(in, 1);//requestCode(请求编号)这个编号为有那个页面跳转回这个页面的(因为有可能有多个页面跳转到这个页面A)
页面B返回跳转到页面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; } }
更多相关文章
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用
- python list.sort()根据多个关键字排序的方法实现
- android单元测试
- Android(安卓)webview与js交互
- Android短信发送器实现方法
- Android(安卓)中the connection to adb is down 解决方法
- android 获取路径目录方法
- android:屏幕自适应