不同Activity之间传递数据--Bundle对象和startActivityForResult方法的实现
首先,由于Activity是Android四大组件之一,如果一个应用程序中包含不止一个Activity,则需要在AndroidManifest.xml文件中进行声明。
例如进行如下的声明(程序中包含两个Activity):
public class EX03_11_1 extends Activity { Bundle bunde; Intent intent; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 载入mylayout.xml Layout */ setContentView(R.layout.myalyout); /* 取得Intent中的Bundle对象 */ intent=this.getIntent(); bunde = intent.getExtras(); /* 取得Bundle对象中的数据 */ String sex = bunde.getString("sex"); double height = bunde.getDouble("height"); /* 判断性别 */ String sexText=""; if(sex.equals("M")) { sexText="男性"; } else{ sexText="女性"; } /* 取得标准体重 */ String weight=this.getWeight(sex, height); /* 设定输出文字 */ TextView tv1=(TextView) findViewById(R.id.text1); tv1.setText("你是一位"+sexText+"\n你的身高是"+height+ "公分\n你的标准体重是"+weight+"公斤"); /* 以findViewById()取得Button对象,并加入onClickListener */ Button b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { /* 回传result回上一个activity */ EX03_11_1.this.setResult(RESULT_OK, intent); /* 关闭activity */ EX03_11_1.this.finish(); } }); } /* 四舍五入的method */ private String format(double num) { NumberFormat formatter = new DecimalFormat("0.00"); String s=formatter.format(num); return s; } /* 以findViewById()取得Button对象,并加入onClickListener */ private String getWeight(String sex,double height) { String weight=""; if(sex.equals("M")) { weight=format((height-80)*0.7); } else{ weight=format((height-70)*0.6); } return weight; } }