简单的整理出5种办法:
1:使用intent直接进行传值
传递:
//创建Intent对象
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
//程序自动创建Bundle,然后将对Intent添加的数据装载在Bundle中
intent.putExtra("name","第二个Activity");
intent.putExtra("num",222);
startActivity(intent);
获取:
Intent intent = getIntent();
String name = intent.getStringExtra("name");
int num = intent.getIntExtra("num",0);
2:创建用于封装数据的Bundle对象,将Bundle对象嵌入Intent中
传递:
//创建用于封装数据的Bundle对象
Bundle bundle = new Bundle();
bundle.putString("name", "第三个Activity");
bundle.putInt("num", 333);
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
//将Bundle对象嵌入Intent中
intent.putExtras(bundle);
startActivity(intent);
获取:
Intent intent = getIntent();
String name = intent.getStringExtra("name");
int num = intent.getIntExtra("num",0);
3:创建public方法,在目标Activity中直接进行取值
传递:
//
public String getName(){
return "第四个Activity";
}
public int getNum(){
return 444;
}
获取:
MainActivity m = new MainActivity();
String name = m.getName();
int num = m.getNum();
4:在目标Acitivity中创建静态成员变量
传递:
FourthActivity.name = "第五个Activity";
FourthActivity.num = 555;
Intent intent = new Intent(MainActivity.this,FourthActivity.class);
startActivity(intent);
获取:
static String name = "FifthActivity";
static int num = 5;
5:获取Application的SharedPreference对象,获取SharedPreference的Editor对象,经过Editor进行写入
//获取Application的SharedPreference对象
SharedPreferences spf = getApplication().getSharedPreferences("info", 0);
//get方法获取值,如果没有存储对应的key-value则返回get方法给的默认值
String name = spf.getString("name", "null");
int num = spf.getInt("num", 0);
boolean boo = spf.getBoolean("boo", false);
//在写入时要先获取SharedPreference的Editor对象,经过Editor进行写入
SharedPreferences.Editor editor = spf.edit();
editor.putString("name", "第六个Activity");
editor.putInt("num", 666);
editor.putBoolean("boo", true);
//put完成后一定要commit(),否则不会生效
editor.commit();
//再使用intent进行页面跳转
获取:
//获取Application的SharedPreference对象
//注意"name"值一定要一致,否则会新建一个SharedPreference对象(本地存储新增一个文件)
SharedPreferences spf = getApplication().getSharedPreferences("info", 0);
String name = spf.getString("name", "null");
int num = spf.getInt("num", 0);
boolean boo = spf.getBoolean("boo", false);
当然,用service,数据库也能进行数据传递,但是总感觉有点大材小用了,这里我也就不做说明了。大家有好的建议和方法可以提出来一起讨论讨论。