ClasscastException when casting to ViewPager

☆樱花仙子☆ 提交于 2020-02-04 03:25:31

问题


I am trying to create an application based on the new ViewPager from the compability library. When I copy the lines from the sample application:

setContentView(R.layout.main);
MyAdapter mAdapter = new MyAdapter(getSupportFragmentManager(), this);
ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);

with the following main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <android.support.v4.view.ViewPager 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/view_pager"
    />
<LinearLayout>

I get a

java.lang.ClassCastException: android.support.v4.app.NoSaveStateFrameLayout

at the line where I cast to ViewPager. Does anyone have an idea why this is happening?


回答1:


Actually the problem ist the old layout inflating problem (look here). For some magic reasons findViewByID doesn't return null here. Instead of returning null it returns a android.support.v4.app.NoSaveStateFrameLayout which is very funny btw.




回答2:


Class cast exceptions occur when you try to cast an object to type which is not compatible with it. So please check whether ViewPager instantiation you are doing is correct or not.



来源:https://stackoverflow.com/questions/7318050/classcastexception-when-casting-to-viewpager

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