2 sachinks SachinKS 于 2013.07.16 11:48 提问

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"

2个回答

cj6585256
cj6585256   2013.07.16 13:15
已采纳
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);
}

这样写就好了

xiaoyaovsxin
xiaoyaovsxin   2013.07.16 14:22

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);
下面。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!