实现FragmentTabhost+ViewPager+Fragment时出现类转换异常

百思不得其解为什么会出现这种类转换错误。也试过不少方法,实在不得其所。
请大触们不吝赐教,谢谢~

运行报错:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wolfgy.news.newsclient, PID: 1109
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wolfgy.news.newsclient/com.wolfgy.news.newsclient.MainActivity}: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.v4.view.ViewPager
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.v4.view.ViewPager
at com.wolfgy.news.newsclient.MainActivity.initView(MainActivity.java:84)
at com.wolfgy.news.newsclient.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5045) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 

备注:这里说的MainActivity.java:84指的是viewPager = (ViewPager)findViewById(R.id.main_viewPager); 这一行。

MainActivity代码如下

 public class MainActivity extends FragmentActivity {
    FragmentTabHost fragmentTabHost;
    SlidingMenu slidingMenu;
    List<Fragment> list = new ArrayList<Fragment>();
    String[] titles={"新闻中心" ,"博客频道","体育频道","科技频道","财经频道","视频","影音娱乐","读书频道","女性频道","男性频道","军事频道","汽车新闻","教育频道","房地产","游戏频道","星座频道"};
    Class[] fragmentArray = {HeadLineFragment.class, BlogFragment.class, SportsFragment.class, ScientistFragment.class,EconomicsFragment.class, VideoFragment.class, EntertainmentFragment.class, ReadingFragment.class, FemaleFragment.class, MaleFragment.class, MilitaryFragment.class,CarsFragment.class, EducationFragment.class, HouseFragment.class, GamesFragment.class,ConstellationFragment.class};
    ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);


        initView();


    }

    private void  initView(){
        fragmentTabHost = (FragmentTabHost)findViewById(R.id.main_fragmentTabHost);
        fragmentTabHost.setup(this,getSupportFragmentManager(),R.id.main_viewPager);

        int count = titles.length;
        for (int i = 0; i < count; i++) {
            TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(titles[i]).setIndicator(getTabItemView(i));
            fragmentTabHost.addTab(tabSpec,fragmentArray[i],null);
            fragmentTabHost.setTag(i);

        }
        fragmentTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String s) {
                int position = fragmentTabHost.getCurrentTab();
                viewPager.setCurrentItem(position);
            }
        });


        //初始化ViewPager
        viewPager = (ViewPager)findViewById(R.id.main_viewPager);
        initPage();
        viewPager.setAdapter(new MainActivityFragmentPagerAdapter(getSupportFragmentManager()));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){

            @Override
            public void onPageSelected(int position) {
                fragmentTabHost.setCurrentTab(position);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    /**
     * 初始化Fragment
     */
    private void initPage(){
        HeadLineFragment headLine = new HeadLineFragment();
        BlogFragment blog = new BlogFragment();
        SportsFragment sports = new SportsFragment();
        ScientistFragment scientistFragment = new ScientistFragment();
        EconomicsFragment economicsFragment = new EconomicsFragment();
        VideoFragment videoFragment = new VideoFragment();
        EntertainmentFragment entertainmentFragment = new EntertainmentFragment();
        ReadingFragment readingFragment = new ReadingFragment();
        FemaleFragment femaleFragment = new FemaleFragment();
        MaleFragment maleFragment = new MaleFragment();
        MilitaryFragment militaryFragment = new MilitaryFragment();
        CarsFragment carsFragment = new CarsFragment();
        EducationFragment educationFragment = new EducationFragment();
        HouseFragment houseFragment = new HouseFragment();
        GamesFragment gamesFragment = new GamesFragment();
        ConstellationFragment constellationFragment = new ConstellationFragment();
        list.add(headLine);
        list.add(blog);
        list.add(sports);
        list.add(scientistFragment);
        list.add(economicsFragment);
        list.add(videoFragment);
        list.add(entertainmentFragment);
        list.add(readingFragment);
        list.add(femaleFragment);
        list.add(maleFragment);
        list.add(militaryFragment);
        list.add(carsFragment);
        list.add(educationFragment);
        list.add(houseFragment);
        list.add(gamesFragment);
        list.add(constellationFragment);
    }

    private View getTabItemView(int i){
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.fragment_tabhost_content_main,null);
        TextView tv = (TextView) view.findViewById(R.id.tabhost_text);
        tv.setText(titles[i]);
        return view;
    }

    private class MainActivityFragmentPagerAdapter extends FragmentPagerAdapter{


        public MainActivityFragmentPagerAdapter(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }


    }
}

activity_main.xml内容如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.wolfgy.news.newsclient.MainActivity">


    <android.support.v4.app.FragmentTabHost
        android:id="@+id/main_fragmentTabHost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v4.app.FragmentTabHost>


    <android.support.v4.view.ViewPager
        android:id="@+id/main_viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

3个回答

wugy315
三汪 问题的关键是我的id引用并没有错误并且我并没有用到FrameLayout。所以这个链接对我没有帮助。
接近 4 年之前 回复

建议使用一个fragment就可以。这样写代码没有可扩展性。

可能v4包有错误?你可以换换v4的版本试试

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问