OnClickListener - 如何正确实现?

时间:2013-07-16 00:29:27

标签: android onclicklistener

好的,这里有一些代码。似乎没有错误但是在Android Studio中运行时我得到“不幸的是,NameOfApplication已停止”。我不知道它有什么问题。

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;
    }
}
}

我还有另一个问题。这是我开始使用Android而且参考api非常大,所以你会推荐哪种最好,最快的学习方法?基本了解其结构等?

2 个答案:

答案 0 :(得分:6)

您必须在setContentView()方法中调用onCreate()之后初始化UI元素,如下所示:

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);
}

答案 1 :(得分:1)

public class MainActivity extends Activity implements OnClickListener {

   //You need the global variables to access the data from onClick, altough you could findViewById inside the onClick itself not to have global variables that exist during the whole activity life.
   private EditText centimeters;
   private EditText inches;

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       //Here you set the view (setContentView(R.layout.activity_main)) so after this line is when you can start looking for your views declared in the xml layout file, "activity_main.xml
       setContentView(R.layout.activity_main);
       //We can look for the views form here
       centimeters = (EditText) findViewById(R.id.editCentimeters);
       inches = (EditText) findViewById(R.id.editInches);
       Button btnConverter = (Button) findViewById(R.id.button);

       btnConverter.setOnClickListener(this);
   }

   ....

其余的相同