Unexpected ClassCastException with findViewById

2019-07-04 16:00发布

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(WordActivity.java:87)

The incriminated line in the Activity :

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

Thanks in advance for your help.

Cheers,

Vincent

3条回答
\"骚年 ilove
2楼-- · 2019-07-04 17:00

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

查看更多
叼着烟拽天下
3楼-- · 2019-07-04 17:01

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

It is most probably a bug.

查看更多
做个烂人
4楼-- · 2019-07-04 17:02

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.

查看更多
登录 后发表回答