添加片段片段,我面临着以下问题:机器人 - 在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);
}
}
}
我想是因为所有的牌都属于MainActivity
,FragmentTransaction
只能添加到一个ViewGroup
与id R.id.actionSheet
。
是否有另一种方式可以将内容添加到具有相同ID的布局中?
'getChildFragmentManager()'解决了我的问题。谢谢! BTW'populate()'在接收到一些数据时由'BroadCastReceiver'调用。对不起,这个信息泄漏。 –