替换显示两个片段的片段

时间:2015-06-02 11:00:07

标签: android android-fragments

我的片段存在问题,它们一起显示,第二个片段显示一个。如何消除,只显示其中一个?

Definiton:

 button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    fr = new avc);
                    FragmentTransaction ft = ((TestingActivity)context).getFragmentManager().beginTransaction();
                    ft.replace(R.id.test, fr);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    ft.addToBackStack(null);
                    ft.commit();

                }
            });

以下容器的定义:

<FrameLayout
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

1 个答案:

答案 0 :(得分:1)

你可以使用这样的东西。创建一个显示片段的函数,并在每次使用不同参数时调用此函数。

例如。如果要显示“HomeFragment”,则调用displayView(0),如果要显示“FindPeopleFragment”,则调用displayView(1)

private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            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");
        }
    }