0

添加片段片段,我面临着以下问题:机器人 - 在containerViewId在ViewPager

MainActivity主要是ViewPager在那里我可以通过卡(Fragment)滑动。该卡片有一个占位符ViewGroup,其中另一个内容(Fragment)在运行时放入。问题是内容只能放在一张卡片上。

MainActivity

public class MainActivity extend FragmentActivity { 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // ... 
     // init ViewPager 
     getViewPager().setAdapter(new CardSelectionAdapter(getSupportFragmentManager())); 
    } 

    // ... 

    private class CardSelectionAdapter extends FragmentPagerAdapter { 
     // ... 

     public Fragment getItem(int position) { 
      return new CardFragment(someData); 
     } 
    } 
} 

CardFragment

public class CardFragment extends Fragment { 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.card, container, false); 
     rootView.findViewById(R.id.actionSheet).setVisibility(View.GONE); 
     return rootView; 
    } 

    public void populate() { 
     // ... 

     Fragment f; 
     switch (type) { 
      case TYPE_A: f = new ActionsAFragment(); break; 
      case TYPE_B: f = new ActionsBFragment(); break; 
      default: f = null; 
     } 

     if (f != null) { 
      // Here should be the main problem when adding Fragment to container/placeholder 
      getFragmentManager().beginTransaction().add(R.id.actionSheet, f).commit(); 
      getView().findViewById(R.id.actionSheet).setVisibility(View.VISIBLE); 

     } 
    } 
} 

我想是因为所有的牌都属于MainActivityFragmentTransaction只能添加到一个ViewGroupid R.id.actionSheet

是否有另一种方式可以将内容添加到具有相同ID的布局中?

回答

1

我没有看到你在哪里打电话populate。您应该更改populate以接受父视图(而不是每次将片段添加到R.id.actionsheet),并从onCreateView中调用它并将其传递给您刚刚创建的视图。这样你就不会在actionSheet中的多个视图中有相同ID的问题。但是,有太多的代码丢失,我不能确切地确定在这里做什么。

顺便说一句,当你在处理嵌套片段 - 在populate里面,你应该使用getChildFragmentManager()而不是getFragmentManager()

+0

'getChildFragmentManager()'解决了我的问题。谢谢! BTW'populate()'在接收到一些数据时由'BroadCastReceiver'调用。对不起,这个信息泄漏。 –