问题描述
- OnClickListener -正确执行
-
执行下面的代码: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);
}
这样写就好了
解决方案二:
EditText centimeters = (EditText) findViewById(R.id.editCentimeters);
EditText inches = (EditText) findViewById(R.id.editInches);
Button btnConverter = (Button) findViewById(R.id.button);
应该放在setContentView(R.layout.activity_main);
下面。
时间: 2025-01-02 08:25:57