我正在制作一个距离转换器应用程序。该代码可以完美编译并且也可以运行。但是当我点击“计算”按钮时,它说
应用程序转换器(进程 com.example.converter)意外停止。请重试
Logcat 截图:
MainActivity.java 代码是:
package com.example.converter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.editText1);
}
// default func
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* Will be executed by clicking on the calculate button because we assigned
* "calculate" to the "onClick" Property!
*/
public void calculate(View view) {
RadioButton mileButton = (RadioButton) findViewById(R.id.radio0);
RadioButton kmhButton = (RadioButton) findViewById(R.id.radio1);
// if the text field is empty show the message "enter a valid number"
if (text.getText().length() == 0) {
// Toast = focused floating view that will be shown over the main
// application
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG)
.show();
} else {
//parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (mileButton.isChecked()) {
text.setText(String.valueOf(convertToMiles(inputValue)));
// uncheck "to miles" Button
mileButton.setChecked(false);
// check "to km/h" Button
kmhButton.setChecked(true);
} else { /* if kmhButton isChecked() */
text.setText(String.valueOf(convertToKmh(inputValue)));
// uncheck "to km/h" Button
kmhButton.setChecked(false);
// check "to miles" Button
mileButton.setChecked(true);
}
}
}
private double convertToMiles(double inputValue) {
// convert km/h to miles
return (inputValue * 1.609344);
}
private double convertToKmh(double inputValue) {
// convert miles to km/h
return (inputValue * 0.621372);
}
}