For some reason, attaching an “internal” OnClickListener to an ImageButton crashes the app. For normal Buttons it works fine – it’s only the ImageButton that crashes it.
public class SomeWidgets extends Activity implements OnClickListener {
....
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
imagebutton = (ImageButton)findViewById(R.id.imagebutton)
imagebutton.setOnClickListener(this);
....
....
}
The above code crashes when clicking the imagebutton. The button1 works fine, even though both are created and attached to the OnClickListener in the exact same way. (It’s the click that crashes it, and not the onClick handling of the click.)
However, if I create a private inner OnClickListener class and attach THAT one to the imagebutton, then it works fine.
Any ideas? Apparently, something goes wrong when attaching the “internal” (this) OnClickListener to an ImageButton, while it works fine when attaching it to a Button.
EDIT: Looks like I found the problem. If I override the onClick like this:
public void onClick(View v) {
if (((Button)v).getText().equals("A button")) {
edittext2.setText(edittext1.getText());
edittext1.setText("");
}
if (imagebutton.getId() == R.id.imagebutton) {
Toast.makeText(SomeWidgets.this, "This is an image button.",
Toast.LENGTH_LONG).show();
}
}
it crashes. However, if I remove the first if{} and only have the imagebutton if there, it works. This is obviously a silly error, but I’d appreciate and explanation as to why 🙂
try with