Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 无法从视图转换为按钮_Android - Fatal编程技术网

Android 无法从视图转换为按钮

Android 无法从视图转换为按钮,android,Android,我这里有一个非常令人沮丧的问题。我有以下代码: Button b = findViewById(android.R.id.button1); 我发现了一个错误: 类型不匹配:无法将窗体视图转换为按钮 但是按钮1是一个按钮!!在我的XML布局文档中,按钮声明如下: <Button android:id = "@+id/button1" android:layout_width = "wrap_content" android:layout_height = "wrap_c

我这里有一个非常令人沮丧的问题。我有以下代码:

Button b = findViewById(android.R.id.button1);
我发现了一个错误:

类型不匹配:无法将窗体视图转换为按钮

但是按钮1是一个按钮!!在我的XML布局文档中,按钮声明如下:

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

为什么我错误地说我的按钮是一个视图,而实际上它是一个按钮。。。是一个谜。

从软件包中删除
android.R
并导入您的
R

import com.companyname.productname.R;
并改变按钮引用

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

您需要将视图强制转换为按钮:

Button b = (Button) findViewById(android.R.id.button1);
详情请浏览


此外,正如其他人回答的那样,id是错误的。

您的错误在这里按钮b=findViewById(android.R.id.button1)


用findViewById(R.id.button1)替换上述行

android.R必须是packagename.RWeird的事情是,在我的一个项目中,我不需要强制转换我的视图,但当我将相同的活动(和布局)复制到另一个不同的项目中时,我确实需要强制转换它们。有人知道为什么吗?我移除了机器人。但是我还是得到了同样的错误?也许你的R.java文件已经损坏了。启动一个新项目,并按按钮b=findViewById(android.R.id.button1)执行;这将解决您的问题您确定删除了软件包
导入android.R
并添加了您的软件包吗?还有更改按钮。。。
Button b = (Button) findViewById(android.R.id.button1);