1

我遇到了我的片段互相重疊的問題。我有一個Android ActionBar選項卡,我正在使用ActionBarSherlock。當我選擇其他選項卡時,ListFragment中的片段放在我的HomeFragment的頂部。這就像它沒有正確分離。更改標籤時重疊片段?

下面是HomeFragment代碼:我想在你的HerbFragment代碼missplaced因爲你應該處理的標籤的東西在活動/片段

public class HerbsFragment extends SherlockListFragment 
          implements ActionBar.TabListener { 

    /** An array of items to display in ArrayList */ 
    String apple_versions[] = new String[]{ 
      "Pancreas", 
      "Blood" 
    }; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                Bundle savedInstanceState) { 
     /** Creating array adapter to set data in listview */ 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(
      getActivity().getBaseContext(), 
      android.R.layout.simple_list_item_1, 
      apple_versions); 

     /** Setting the array adapter to the listview */ 
     setListAdapter(adapter); 
     View v = inflater.inflate(R.layout.activity_main, container, false); 
     return super.onCreateView(inflater, container, savedInstanceState); 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 
     /** Setting the multiselect choice mode for the listview */ 
     getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    } 

    @Override 
    public void onTabSelected(Tab tab, FragmentTransaction ft) { 
     ft.add(android.R.id.content, this,"apple"); 
     ft.attach(this); 
    } 

    @Override 
    public void onTabUnselected(Tab tab, FragmentTransaction ft) { 
     ft.detach(this); 
    } 

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

} 

回答

1

public class HomeFragment extends SherlockFragment 
          implements ActionBar.TabListener { 

    private View homeView; 

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

    @Override 
    public void onTabSelected(Tab tab, FragmentTransaction ft) { 
     ft.add(android.R.id.content, this,"apple"); 
     ft.attach(this); 
    } 

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

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

} 

代碼HerbFragment有標籤,不在標籤中。你可以處理你的HomeFragment兩種不同的方式:

- 當一個標籤的用戶點擊,取代目前的片段:只是改變這一個ft.replace(和刪除ft.attach線):

ft.add(android.R.id.content, this,"apple"); 
ft.attach(this); 

- 附加新的片段並分離之前的內容:如果知道它是哪個片段,請從附加的片段中獲取參考,並使用與附加片段相同的方法將其分開。