片段景观如何正确替换

时间:2013-02-20 19:05:07

标签: android android-layout android-fragments

我有一个包含许多片段的应用。这是水平模式下的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment android:name="com.map.manager.ListUser"
          android:id="@+id/listuser_fragment"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="match_parent" />

    <fragment android:name="com.map.manager.DetailApp"
          android:id="@+id/detailapp_fragment"
          android:layout_weight="2"
          android:layout_width="0dp"
          android:layout_height="match_parent" />   

</LinearLayout>

我可以看到我的片段是正确的,但如果我这样做:

            DetailUser appFrag = (DetailUser)
                    getSupportFragmentManager().findFragmentById(R.id.detailuser_fragment);

            if (appFrag != null) {
                // If article frag is available, we're in two-pane layout...

                // Call a method in the ArticleFragment to update its content
                appFrag.updateAppointmentView(position);

            } 
            else {
            DetailUser dtuser = new DetailUser();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.detailapp_fragment, dtuser);
            transaction.commit();

我可以替换片段,但我可以看到旧片段到背景中.. 我读THIS我无法替换静态片段但是如何动态添加它? (多个进入水平模式..)我可以在不知道旧片段的情况下替换片段吗?

1 个答案:

答案 0 :(得分:0)

片段容器:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:id="@+id/fragmentLayout"
    >

     <FrameLayout
        android:id="@+id/framelayout1"
        android:layout_width="313dp"
        android:layout_height="match_parent" >
     </FrameLayout>

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

</LinearLayout>



//Adding Detailuser fragment to framelayout1:

    DetailUser dtuser = new DetailUser();
            FragmentTransaction transaction =    getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.framelayout1, dtuser);
            transaction.commit();
//Adding another fragment to framelayout1:

    Fragment frag = new Fragment();
            FragmentTransaction transaction =    getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.framelayout2, frag);
            transaction.commit();

//Replacing fragment in framelayout:

    Fragment2 frag2 = new Fragment2();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.framelayout1, frag);
                transaction.commit();