如何在Android上的ViewPager视图中替换片段



我有ViewPager, PagerAdapter(不是FragmentPagerAdapter)和2个视图。我需要在第二个视图中插入一些片段。问题是FragmentManager.begin().replace(id, fragment).commit()需要视图容器id,但无法找到,因为PagerAdapter动态地做到了。

您应该在每个适配器上都这样做-更改PagerAdapter中的数据集并调用

notifyDataSetChanged();

你将有你的自定义布局文件作为ViewPager Item,你将在

中指定
    public Object instantiateItem(View collection, int position) {
PagerAdapter的

方法。这样你就可以膨胀你的自定义视图,并在其中添加你的片段。

:

 @Override
        public Object instantiateItem(View collection, int position) {
            View layout; 
            LayoutInflater mInflater =  (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            switch (mItems.get(position).type) {
            case TAB_ABOUT:
                layout  = mInflater.inflate(R.layout.detail_pager_item_about, null);
                // Commit your fragment Here. 
// Do check if it is already there to avoid multiple commits.
    ((ViewPager) collection).addView((View)layout,0);
        return layout;          
}

添加片段到视图:

   FragmentTransaction ft = getFragmentManager().beginTransaction();
   ft.add(CONTENT_VIEW_ID, newFragment).commit();

最新更新