4

我尝试安装在我的应用程序以下导航:里面ViewPager片段替换ListFragment与标签

实际情况:ViewPager +选项卡列表之间刷卡:

  • ListFragment一个
  • ListFragment乙

期望的条件: ViewPager +标签:

  • ListFragment甲onListItemSelected替换ListFragment A和DetailFragment甲
  • ListFragment乙onListItemSelected与DetailFragment乙

的目标是显示标签导航内部的细节片段替换ListFragment乙。我无法用detailFragment替换fragmentList(fragmentList没有自定义布局,因此也没有ID,我不知道该怎么做)。 此外,开始一个新的活动隐藏标签栏。

有人可以帮我吗?

回答

14

我会做一个包装片段,知道要显示什么 - 列表或细节。这将与ViewPager完全分离 - 寻呼机只知道它持有包装碎片,并且这些将自己管理它们的内容。

实施将沿着这些路线:

public class WrapperFragment extends Fragment { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     MyListFragment list = new MyListFragment(); 
     list.setListAdapter(adapter); 
     list.setOnItemClickListener(new OnItemClickListener() { 
      @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { 
       // Create details fragment based on clicked item's position 
       Fragment details = new Fragment(); 
       getChildFragmentManager() 
        .beginTransaction() 
        .replace(R.id.container, details) 
        .addToBackStack(null) 
        .commit(); 
      } 
     }); 

     getChildFragmentManager() 
      .beginTransaction() 
      .add(R.id.container, list) 
      .commit(); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     // There has to be a view with id `container` inside `wrapper.xml` 
     return inflater.inflate(R.layout.wrapper, container, false); 
    } 

    public class MyListFragment extends ListFragment { 

     private OnItemClickListener listener; 

     public void setOnItemClickListener(OnItemClickListener l) { 
      this.listener = l; 
     } 

     @Override 
     public void onListItemClick(ListView l, View v, int position, long id) { 
      if(listener != null) { 
       listener.onItemClick(l, v, position, id); 
      } 
     } 
    } 
} 

wrapper.xml。想法是,WrapperFragment必须提供一个布局,其中包含一个编号为container的视图 - 因为我们正在使用该编号来查看子片段 - MyListFragmentDetailsFragment

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

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

</FrameLayout> 

的另一种方式。这应该工作,但你必须要尝试了这一点(布局有id本身,而不是用ID container孩子):

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"/> 
+0

请问布局包装这个样子?我得到了onCreateView的InflateException。 2013-03-10 12:22:22

+1

添加了'wrapper.xml'的示例。让我知道如果你有这个问题 – mindeh 2013-03-10 12:48:52

+0

谢谢,它似乎工作正常。 – 2013-03-10 14:36:50