您的位置:首页 > 其它

不同 Activity 之间的数据传递

2013-12-21 17:25 183 查看
主activity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
Intent intent=new Intent(); //声明一个intent
intent.setClass(MainActivity.this, main2.class); //设置intent
Bundle bundle=new Bundle(); //声明一个bundle
RadioButton rb=(RadioButton)findViewById(R.id.radio0);
String sex="";
if(rb.isChecked()) //获取大家选中的是男m还是女
w sex="M";
else
sex="W";
bundle.putString("sex", sex); //把获取的值放到bundle中

EditText edittext=(EditText)findViewById(R.id.editText1);
double height=Double.parseDouble(edittext.getText().toString()); //获取身高
bundle.putDouble("height", height); //把获取的值放到bundle中
intent.putExtras(bundle); //把bundle放到intent中
startActivity(intent);

}
});
}

显示activity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
TextView tv=(TextView)findViewById(R.id.textView9);
Bundle bundle=this.getIntent().getExtras(); //把intent中获取值
String sex="";
if(bundle.getString("sex").equals("M")) //获取男或女
sex="男";
else
sex="女";
Double height=bundle.getDouble("height"); //获取身高

tv.setText("你的姓别:"+sex+"\n你的身高:"+height+"\n你的标准体重是"+ weight + "公斤");

}

/* 四舍五入的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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: