Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Cannot cast from View to Button

I just started working with the Android, but seem to have come across a problem that I simply can't find the answer to. I get the error "Cannot cast from View to Button" on this line :

Button myButton = (Button)findViewById(R.id.my_button);

I've tried many different things to get it going, and I've searched for the answer, but for some reason it just refuses to work right. If anybody could point me in the right direction it'd be most appreciated.

Thank in advance.

like image 869
Mike Avatar asked Jun 24 '26 10:06

Mike


2 Answers

try this,

android.widget.Button myButton = (android.widget.Button)findViewById(R.id.my_button); 
like image 111
sanjay Avatar answered Jun 26 '26 00:06

sanjay


Is the exception a ClassCastException? If so then the view you are finding with the id my_button isn't a button. If it's a NullPointerException then there is no view with the id my_button. This could be cause by not calling setContent() before you try to find the views.

like image 45
CaseyB Avatar answered Jun 25 '26 23:06

CaseyB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!