我是 Java Android 编程的新手。我想将一个按钮与一个侦听器集成,但我无法让它工作。
public class MainClass extends Activity implements OnClickListener{
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.editText1);
Log.e("AOWN", "STARTED !");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View view){
Log.e("AOWN", "I just clicked !");
}
}
我知道如何迭代所有按钮(R 类),但不会调用 onClick 方法!
我试图添加一个测试按钮并为其附加一个侦听器,它正在工作,但它的代码要多得多,而且我很懒。
这是可行的,但是要编写更多代码,我正在关注一本书,其中使用 onClick() 方法触发了该操作。
public class MainClass extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("AOWN", "STARTED !");
// Like in java with SelectionListener
Button bTest = (Button)findViewById(R.id.button1);
bTest.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Log.e("AOWN", "It's working but it's much more to code and I'm freakn lazy.");
}
});
}
}