刚刚开始接触安卓开发,将自己的学习笔记拿来分享,有错的请指出!共同进步~~
Activity跳转(Activity1-->Activity2)
1.startActivity
方法1:
//Activity 1
EnergyTask energyTask;//EnergyTask需要实现Serializable
Intent intent = new Intent(Activity1.this,Activity2.class);
Bundle bundle = new Bundle();
bundle.putSerializable("EnergyTask ",energyTask);
bundle.purString("",……);//需要传递的值
intent.putExtras(bundle);
startActivity(intent);
//Activity 2
Intent intent = getIntent;
Bundle bundle = intent.getExtras();
energyTask1 = (EnergyTask) bundle.getSerializable("EnergyTask");
……
方法2:
//Activity 1
//直接将要传递的值加到该方法中
Activity2.startActivity(getActivity,energyTask,……);
//Activity 2
//将Activity1中传递过来的值加入Bundle
public static void startActivty(Activity fromActivity,EnergyTask energyTask,……){
Intent intent = new Intent(fromActivty,Activity2.class);
Bundle bundle = new Bundle();
bundle.putSerializable("EnergyTask",enegyTask);
bundle.putString("",……);
intent.putExtras(bundle);
fromActivity.startActivty(intent);
}
//获取Bundle中的值
Bundle bundle = getIntent().getExtras();
if(bundle != null){
EnergyTask energyTask1 = (EnergyTask) bundle.getSerializable("EnergyTask");
……
}
2. startActivityForResult
//Activity 1
EnergyTask energyTask;//EnergyTas需要实现Serializable
Intent intent = new Intent(Activity1.this,Activity2.class);
Bundle bundle = new Bundle();
bundle.putSerializable("EnergyTask ",energyTask);
bundle.purString("",……);
intent.putExtras(bundle);
startActivityForResult(intent,100);
//Activity 2
//获取从Activity1传递过来的数据
Intent intent;
intent = getIntent;
Bundle bundle = intent.getExtras();
energyTask1 = (EnergyTask) bundle.getSerializable("EnergyTask");
……
//Activity 2
//向Activity1返回数据
intent = new Intent(Activity2.this,Activity1.class);
Bundle b = new Bundle();
b.putLong("Status",status);
intent.putExtras(b);
Activity2.this.setResult(101,intent);
//Activity 1
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(arg0, arg1, arg2);
if(requestCode == 100){
if(resultCode == 101){
Bundle bundle =data.getExtras();
long status = bundle.getLong("Status");
……
}
}
}