添加选项卡导航到我的片段

时间:2015-10-15 03:01:54

标签: java android android-fragments

我是Android开发的新手。我已经为我的Activity创建了一个Tab导航,但是现在我将代码转移到我的Fragment for my project中,我遇到了一些错误。有人可以帮助我在片段中正确地做到这一点。

注意:我在frmSlide和fragmentFeedFragment上使用了import android.support.v4.app.Fragment;

我的frmSlide代码就是这个

public class frmSlide extends AppCompatActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;
ViewPager viewPager;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    // update the main content by replacing fragments
    fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position + 1)).commit();

    Fragment fragment;
    switch (position + 1) {
        case 1:
            //Profile
            fragment = new fragmentProfileFragment();
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
            break;
        case 2:
            //startActivity(new Intent(this, fragmentFeed.class));
            //Feed
            fragment = new fragmentFeedFragment();
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
            break;
        case 3:
            //Settings
            fragment = new fragmentSettingsFragment();
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
            break;
        case 4:
            //About
            fragment = new fragmentAboutFragment();
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
            break;
    }
    Log.d("MySlide", "onNavigation " + position);

}

//SELECTED/CLICKED MENU ON SLIDE MENU
public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            //Toast.makeText(frmSlide.this, "Profile was selected", Toast.LENGTH_SHORT).show();
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            //Toast.makeText(frmSlide.this, "Feed was selected", Toast.LENGTH_SHORT).show();
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            //Toast.makeText(frmSlide.this, "Settings was selected", Toast.LENGTH_SHORT).show();
            break;
        case 4:
            mTitle = getString(R.string.title_section4);
            //Toast.makeText(frmSlide.this, "About was selected", Toast.LENGTH_SHORT).show();
            break;
        case 5:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to Logout?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                            startActivity(new Intent(frmSlide.this, MainActivity.class));//Close  this Activity for example: MyActivity.java
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // some code if you want
                            dialog.cancel();
                            restoreActionBar();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
            break;

        }
}


public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.frm_slide, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_frm_slide, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((frmSlide) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

}

这是我的fragmentFeedFragment。

public class fragmentFeedFragment extends Fragment implements ActionBar.TabListener {
ViewPager viewPager;
ActionBar actionBar;

public fragmentFeedFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_fragment_feed, container, false);
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    viewPager = (ViewPager) getView().findViewById(R.id.pager);
    viewPager.setAdapter(new MyFeedAdapter(getFragmentManager()));
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            Log.d("Vivz", "onTabSelected at " + "position " + position + "from " + positionOffset + "pixels # " + positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
            //Log.d("Vivz", "onTabSelected at " + "position " + position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar();
    //actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab tab1 = actionBar.newTab();
    tab1.setText("JOY");
    tab1.setTabListener(this);

    ActionBar.Tab tab2 = actionBar.newTab();
    tab2.setText("SADNESS");
    tab2.setTabListener(this);

    ActionBar.Tab tab3 = actionBar.newTab();
    tab3.setText("ANGER");
    tab3.setTabListener(this);

    actionBar.addTab(tab1);
    actionBar.addTab(tab2);
    actionBar.addTab(tab3);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

}

类MyFeedAdapter扩展了FragmentPagerAdapter {

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

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;
    if (position==0){
        fragment = new fragmentJoyFragment();
    }
    if (position==1){
        fragment = new fragmentSadnessFragment();
    }
    if (position==2){
        fragment = new fragmentAngerFragment();
    }
    return fragment;
}

@Override
public int getCount() {
    return 3;
}

}

这是出现的错误

10-15 11:11:37.781  16034-16034/com.example.agnes.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: com.example.agnes.myapplication.frmSlide cannot be cast to android.support.v7.app.ActionBarActivity
        at com.example.agnes.myapplication.fragmentFeedFragment.onActivityCreated(fragmentFeedFragment.java:54)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1970)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1051)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:213)
        at android.app.ActivityThread.main(ActivityThread.java:4787)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
        at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

在fragmentFeedFragment.java:54中,
更改

actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar();

actionBar = getActionBar();

答案 1 :(得分:0)

我通过将AppCompatActivity从我的frmSlide更改为ActionBarActivity来解决此问题。