我想使用我通过在其他 Activity 中一起计算 3 个数字而从我的代码中获得的变量(答案),我想使用我在 Activity 2 中的 Activity 1 的先前计算中获得的答案来计算一个新变量。我试图在 Internet 上进行搜索,但搜索内容并不多,或者我只是将文本值传递到另一个页面并替换它。我以某种方式设法在第一时间得到了正确的想法,但我的模拟器无法正常工作。
这是我的代码,我希望我让它变得合理。
Activity 1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_male);
age =(TextView)findViewById(R.id.age);
height=(TextView)findViewById(R.id.heigth);
weight =(TextView)findViewById(R.id.weigth);
result =(TextView)findViewById(R.id.result);
eage=(EditText)findViewById(R.id.eage);
eheight=(EditText)findViewById(R.id.eheight);
eweight=(EditText)findViewById(R.id.eweight);
calculate=(Button)findViewById(R.id.calculate);
back =(Button)findViewById(R.id.back);
next =(Button)findViewById(R.id.next);
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
double n1=Double.parseDouble(eage.getText().toString());
double n2=Double.parseDouble(eheight.getText().toString());
double n3=Double.parseDouble(eweight.getText().toString());
double ans=(90+4.8*n2+13.4*n3-5.7*n1);
result.setText("Your BMR is "+ans);
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MALE.this,MainActivity.class);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MALE.this, MALERUN.class);
double n1=Double.parseDouble(eage.getText().toString());
double n2=Double.parseDouble(eheight.getText().toString());
double n3=Double.parseDouble(eweight.getText().toString());
double ans=(90+4.8*n2+13.4*n3-5.7*n1);
result.setText("Your BMR is "+ans);
i.putExtra("answer",ans);
startActivity(i);
}
});
}
Activity 2
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_malerun);
calculate=(Button)findViewById(R.id.calculate);
back =(Button)findViewById(R.id.back);
next =(Button)findViewById(R.id.next);
result =(TextView)findViewById(R.id.result);
time=(EditText)findViewById(R.id.time);
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (time.getText().equals(0));
Intent i = getIntent();
double[] n1=i.getDoubleArrayExtra("answer");
double ans = (n1*1.2);
}
});
}
最佳答案
您可以使用Intent
传递数据
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("ANSWER", answer);
startActivity(intent);
并在 Activity 2.class 中创建
double answer = getintent().getDoubleExtra("ANSWER", 0.0);
关于android - 如何使用从一个 Activity 到另一个 Activity 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566820/