如何正确地将片段初始化为null?

时间:2016-05-11 02:58:07

标签: java android android-fragments

所以这里是代码:

private void selectItem(int position) {

        Fragment fragment = null;

        switch (position) {
            case 0:
                fragment = new HomeFragment();
                break;
            case 1:
                fragment = new DoctorFragment();
                break;
            case 2:
                fragment = new HospitalFragment();
                break;
            case 3:
                fragment = new SpecialClinicFragment();
                break;
            case 4:
                fragment = new PharmacyFragment();
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();


            //the parameter "fragment" in this line of code gives an error message.
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();



            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        } else {
            Log.e("MainActivity", "Error in creating fragment");
        }

enter image description here

好像我没有正确初始化片段实例。

错误消息是"错误的第二个参数类型"但我很确定我输入了正确的参数。

1 个答案:

答案 0 :(得分:0)

问题不在于论证。你使用了Fragment android.support.v4库,但你在android.app.fragment上进行交易。

解决方案:

导入android.app.fragment而不是android.support.v4.fragment

因为你无法与support.v4库和android.app。*

混淆