2017-05-07 151 views
0

我遇到了我的片段問題,但不知道爲什麼。我在主要活動中有兩個片段。一邊(右邊)在片段上有一個微調器,在那個片段中,我替換了微調器顯示的片段。左側顯示了使用陣列適配器顯示數據的列表視圖。替換片段刪除另一片段

問題是,無論何時我替換左側的片段,右側的片段消失,我不知道爲什麼會這樣做。

這是我的微調更換左側片段代碼:

personSelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

     @Override 
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

      if (position == 0) { 

       personType = "Student"; 

       StudentFragment studentFrag = StudentFragment.newInstance(); 
       getFragmentManager().beginTransaction() 
         .replace(R.id.form, studentFrag) 
         .commit(); 

      } else if (position == 1) { 

       personType = "Teacher"; 

       TeacherFragment teacherFrag = TeacherFragment.newInstance(); 
       getFragmentManager().beginTransaction() 
         .replace(R.id.form, teacherFrag) 
         .commit(); 

      } else if (position == 2) { 

       personType = "Administrator"; 

       AdminFragment adminFrag = AdminFragment.newInstance(); 
       getFragmentManager().beginTransaction() 
         .replace(R.id.form, adminFrag) 
         .commit(); 

      } // end if/else 

     } // end personSelection 

     @Override 
     public void onNothingSelected(AdapterView<?> parent) {} 

    }); // end selection 

右側片段被用微調器旁邊顯示新添加的數據到數組列表按鈕刷新,這就是隻有該片段被使用的時間。

一個視覺展現我的意思。

  • 應用程序啓動時工作正常:

enter image description here

  • 選擇微調後:(刷新按鈕並不要麼在此之後的工作)

enter image description here

這是主要活動在xml:

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 

    <Spinner 
     android:layout_height="40dp" 
     android:id="@+id/person_spinner" 
     android:entries="@array/child" 
     android:layout_width="170dp" /> 

    <Button 
     android:text="Button" 
     android:id="@+id/refresh_button" 
     android:drawableStart="@android:drawable/stat_notify_sync" 
     android:drawableTint="#000000" 
     android:layout_width="45dp" 
     android:layout_height="50dp" /> 
    </LinearLayout> 

    <fragment 
    android:name="com....StudentFragment" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight=".4" 
    android:id="@+id/form" 
     tools:layout="@layout/student_fragment" /> 

</LinearLayout> 

<fragment 
    android:name="com....DetailFragment" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:layout_weight=".7" 
    android:id="@+id/frame_detail" 
    tools:layout="@layout/fragment_detail"/> 

回答

0

也許嘗試動態更換兩個(左和右片段)。不要在xml佈局中定義任何片段。相反,使用2個FrameLayouts作爲碎片的容器,並根據需要僅在代碼中動態添加所需的碎片。

0

我修好了。我不應該試圖替換一個片段,這會將其移除並與主要活動的整個佈局混淆。所以我做的是,在主體中一起創建所有片段,並在線性佈局內的相對佈局中添加它們。在onCreate方法,我只是改變了他們的知名度,以顯示我想要的和隱藏其他人取決於微調選擇。現在整個應用程序沒有任何問題。