Cannot convert from View to Button

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

Very frustrating problem I have here. I have this code:

Button b = findViewById(android.R.id.button1); 

And I'm getting this error on it:

Type mismatch: cannot convert form View to Button

But button1 is a button!! In my XML layout document the button has been declared like this:

<Button    android:id = "@+id/button1"    android:layout_width = "wrap_content"    android:layout_height = "wrap_content"    android:text = "Next Activity"  /> 

And in my R.java:

public static final class id {    public static final int button1=0x7f050000; } 

Why I get and error saying that my button is a view when it actually is indeed a button... is a mystery.

回答1:

You need to cast the view to Button:

Button b = (Button) findViewById(android.R.id.button1); 

More details at http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

In addition, as answered by others, the id is wrong.



回答2:

remove android.R from packages and import your R.

import com.companyname.productname.R; 

and change also button refrence

Button b = (Button)findViewById(R.id.button1);                                 ^^^^^^^^^^^^ 


回答3:

Your mistake is here-Button b = findViewById(android.R.id.button1);

Replace the above line by findViewById(R.id.button1);



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!