執行下面的代碼:
public class MainActivity extends Activity implements OnClickListener {
EditText centimeters = (EditText) findViewById(R.id.editCentimeters);
EditText inches = (EditText) findViewById(R.id.editInches);
Button btnConverter = (Button) findViewById(R.id.button);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnConverter.setOnClickListener(this);
}
@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;
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.button:
double c = Double.valueOf(centimeters.getText().toString());
double i = c * 0.393701;
inches.setText(String.valueOf(i));
break;
default:
break;
}
}
}
就會出錯:"Unfortunately, NameOfApplication has stopped"
EditText centimeters;
EditText inches;
Button btnConverter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
centimeters = (EditText) findViewById(R.id.editCentimeters);
inches = (EditText) findViewById(R.id.editInches);
btnConverter = (Button) findViewById(R.id.button);
btnConverter.setOnClickListener(this);
}
這樣寫就好了