I am new to the onClickListener. I am trying to learn it using example code from stackoverflow and android (http://developer.android.com/reference/android/widget/Button.html), but I cannot get my code to compile. I even copy and pasted the code directly from android, and it still would not compile. So my question is:
Can you recommend a beginners tutorial to learn the onClickListener in depth? Thanks.
Even when I used the identical code from android, I would still get the same errors. But in case its relevant to my question above, here is my code and error:
package com.evorlor.testcode;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class Button extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
Button btnTest = (Button) findViewById(R.id.btnTest);
btnTest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
}
Cannot cast from View to Button
That tutorial snippet refers to the android Button class. You wrote your own class and named it “Button” – hence, the cast won’t work. Your button extends “Activity” which isn’t a subclass of view, so you can’t cast a View to your Button class.
Rename your class, and import android.widget.button