Reputation: 11
Could someone please explain why I am getting this error?
Java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.View$OnKeyListener
Below is the java code. I am trying to follow a tutorial and I can't get it started. The RAZR emulator only shows Unfortunately JimYamba quit working
. The error is from Eclipse LogCat.
package com.example.jimyamba;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;;
public class MainActivity extends Activity implements OnClickListener{
Button buttonUpdate;
EditText editStatus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status);
buttonUpdate = (Button)findViewById(R.id.button_update);
editStatus = (EditText) findViewById(R.id.edit_status);
buttonUpdate.setOnKeyListener((OnKeyListener) this.buttonUpdate);
}
@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;
}
public void onClick(View v){
String statusText = editStatus.getText().toString();
Log.d("StatusActivity","onClicked with text:" + statusText);
}
}
Upvotes: 0
Views: 1504
Reputation: 2362
What are you trying to accomplish? You have implemented OnClickListener so if all you need is to execute what's inside of the onClick method with an OnClickListener, just change
buttonUpdate.setOnKeyListener((OnKeyListener) this.buttonUpdate);
With
buttonUpdate.setOnClickListener(this);
Or if you want OnKeyListener do what techiServices suggested
Upvotes: 1
Reputation: 8533
buttonUpdate.setOnKeyListener((OnKeyListener) this.buttonUpdate);
should be
buttonUpdate.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
});
Look at http://developer.android.com/reference/android/view/View.OnKeyListener.html
Upvotes: 1
Reputation: 1652
The error is in the line buttonUpdate.setOnKeyListener((OnKeyListener) this.buttonUpdate);
. Just as the error says, you cannot cast a button to an OnKeyListener. Explicit casting requires a relationship via class hierarchy - Button and OnKeyListener are not related (OnKeyListener is an interface).
If you want to maintain your set up you can create a class that extends Button and Implements OnKeyListener. You will have to edit you xml to have your custom view in place of the button.
Upvotes: 1