我是一个初学者,我正在尝试制作一个 Intent Calculator,这意味着我正在通过 Intent extras 添加输入并开始一个新的活动来计算输入。最后,我尝试使用 onActivityResult() 接收结果。问题是我已将结果设置为文本视图,文本视图将其检测为双精度值(从默认文本显示 0.0)。我无法理解问题出在哪里,因为 Logcat 甚至没有错误。下面是我的代码。当我按下按钮时,它只显示 0.0。不管我点击多少次。我也在练习 Intents,所以只尝试了基本的 Intents。请帮助我。
public class InputActivity extends Activity {
final int CALCULATION_COMPLETE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input);
final EditText num1 = (EditText) findViewById(R.id.num1_edit);
final EditText num2 = (EditText) findViewById(R.id.num2_edit);
Button add = (Button) findViewById(R.id.resultButton);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String firstNum = num1.getText().toString();
String secondNum = num2.getText().toString();
Intent resultIntent = new Intent(InputActivity.this,ResultActivity.class);
resultIntent.putExtra("first", firstNum);
resultIntent.putExtra("second", secondNum);
startActivityForResult(resultIntent, CALCULATION_COMPLETE);
}
});
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent d){
super.onActivityResult(reqCode, resCode, d);
TextView result = (TextView) findViewById(R.id.result);
if(reqCode == CALCULATION_COMPLETE && resCode == RESULT_OK){
Intent resultData = getIntent();
Double addResult = resultData.getDoubleExtra("result", 0);
String resultStr = addResult.toString();
result.setText(resultStr);
}
}
}
public class ResultActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent calcIntent = getIntent();
String firstStr = calcIntent.getStringExtra("first");
String secondStr = calcIntent.getStringExtra("second");
Double firstNum = Double.parseDouble(firstStr);
Double secondNum = Double.parseDouble(secondStr);
Double addResult = firstNum + secondNum;
Intent result = new Intent();
result.putExtra("result", addResult);
setResult(RESULT_OK, result );
finish();
}
}