开发者

Unexpected ClassCastException with findViewById

开发者 https://www.devze.com 2023-02-02 03:52 出处:网络
I play around with the \'searchable dictionnary\' to get into Android development. My problem is that I get some ClassCastException when modifying the XML layouts.

I play around with the 'searchable dictionnary' to get into Android development.

My problem is that I get some ClassCastException when modifying the XML layouts.

My guess is that the R file is outdated, but what is weird is that I still have the problem even after recreating it.

Here are the releveant piece of code and log :

The log file :

Caused by: java.lang.ClassCastException: android.widget.ImageButton E/AndroidRuntime( 438): at eu.accleaner.android.WordActivity.onCreate(Wo开发者_运维知识库rdActivity.java:87)

The incriminated line in the Activity :

mDefinition = (TextView) findViewById(R.id.definition);

Thanks in advance for your help.

Cheers,

Vincent


From what it looks like, there's an ImageButton in the XML with an id of "definition", and you're trying to cast it to a TextView. Change your TextView cast to ImageButton.


I had similar issue. R.java generates IDs based on android:id in xml:
public static final int imageButton01=0x7f050001;
public static final int definition=0x7f050002;

When I add new imagebutton R.java will update to
public static final int imageButton01=0x7f050001;
public static final int imageButton02=0x7f050002;
public static final int definition=0x7f050003;

Due to synchronization problem R.id.definition returns old ID 0x7f050002 in mDefinition = (TextView) findViewById(R.id.definition); But it corresponds to another element (ImageButton02) according to updated R.java.

So we have ClassCastException


Workaround to fix: Assign some new 'id' value in Layout XML and findViewById().

It is most probably a bug.

0

精彩评论

暂无评论...
验证码 换一张
取 消