对于类型MoviesFragment,getsupportfragmentmanager未定义

时间:2014-06-10 19:22:28

标签: java android android-support-library

我正在创建一个Android应用程序。在一个类中,我正在扩展片段,我在标题中收到错误。这是代码:

    import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ashat.jaiswal.trr.adapter.TabsPagerAdapter;

public class MoviesFragment extends Fragment implements ActionBar.TabListener{

    //public MoviesFragment(){}
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;

    private String[] tabs = { "InTheaters", "Upcoming", "Search" };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_movies, container, false);

        viewPager = (ViewPager)rootView.findViewById(R.id.pager);
        actionBar = getActivity().getActionBar();
        mAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);   

        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });


        return rootView;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }
}

问题是当我扩展片段活动时,它试图删除覆盖符号onCreate方法。没有它,我收到这个错误。有人可以告诉我一些解决方案吗?

这是完整的logcat:

06-11 00:23:57.196: E/AndroidRuntime(20226): FATAL EXCEPTION: main
06-11 00:23:57.196: E/AndroidRuntime(20226): java.lang.RuntimeException: Unable to start activity ComponentInfo{ashat.jaiswal.trr/ashat.jaiswal.trr.MainActivity}: java.lang.ClassCastException: ashat.jaiswal.trr.MainActivity cannot be cast to android.support.v4.app.FragmentActivity
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread.access$600(ActivityThread.java:156)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.os.Looper.loop(Looper.java:153)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread.main(ActivityThread.java:5297)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at java.lang.reflect.Method.invokeNative(Native Method)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at java.lang.reflect.Method.invoke(Method.java:511)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at dalvik.system.NativeStart.main(Native Method)
06-11 00:23:57.196: E/AndroidRuntime(20226): Caused by: java.lang.ClassCastException: ashat.jaiswal.trr.MainActivity cannot be cast to android.support.v4.app.FragmentActivity
06-11 00:23:57.196: E/AndroidRuntime(20226):    at ashat.jaiswal.trr.MoviesFragment.onAttach(MoviesFragment.java:28)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:844)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.BackStackRecord.run(BackStackRecord.java:694)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.Activity.performStart(Activity.java:5131)
06-11 00:23:57.196: E/AndroidRuntime(20226):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2279)
06-11 00:23:57.196: E/AndroidRuntime(20226):    ... 11 more
06-11 00:23:57.280: E/AppErrorDialog(498): Failed to get ILowStorageHandle instance

MainActivity.java

   import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import ashat.jaiswal.trr.adapter.NavDrawerListAdapter;
import ashat.jaiswal.trr.model.NavDrawerItem;

public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {

   ==========================This part Shows errors===================================
        case 0:
            fragment = new MoviesFragment();
   ==========================This part Shows errors===================================
        case 1:
            fragment = new TVFragment();
            break;
        case 2:
            fragment = new TheTopListFragment();
            break;
        case 3:
            fragment = new ShareFragment();
            break;
        case 4:
            fragment = new MoreFragment();
            break;
        case 5:
            fragment = new AboutUsFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

1 个答案:

答案 0 :(得分:0)

您的问题是您正在尝试将支持库与非支持库混合,这导致ClassCastExceptions。在这种情况下,当您可能需要android.support.v4.app.Fragment时,您正在使用android.app.Fragment。在MoviesFragment中,在导入语句中更改以下内容。

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ashat.jaiswal.trr.adapter.TabsPagerAdapter;

但是,如果您计划定位少于11的API版本,则需要重新编写大量代码。在这种情况下,您需要使用FragmentActivity代替Activity