无法从视图转换为按钮

无法从视图转换为按钮

本文介绍了无法从视图转换为按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到的问题非常令人沮丧.我有以下代码:

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

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

我收到此错误消息:

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

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"
/>

在我的R.java中:

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.

推荐答案

您需要将视图投射到Button:

You need to cast the view to Button:

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

更多详细信息,请参见 http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

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

此外,正如其他人回答的那样,该ID是错误的.

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

这篇关于无法从视图转换为按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:45