当所选的单选按钮改变时,我有一个无线电组可以改变活动中的碎片。我有这段代码:
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.main_menu1:
showOffersFragment();
break;
case R.id.main_menu2:
openMap();
break;
case R.id.main_menu3:
showProductsFragment();
break;
}
}
private void showProductsFragment() {
fm = getFragmentManager();
ft = fm.beginTransaction();
if (productsFragment == null) {
bundle = new Bundle();
bundle.putSerializable(ActivityConstants.PRODUCT_ITEMS, products);
productsFragment = new ProductFragment();
productsFragment.setArguments(bundle); ft.add(R.id.main_frag_container, productsFragment, "products");
} else {
//TODO
ft.replace(R.id.main_frag_container, productsFragment, "products");
productsFragment.loadList(products);
}
ft.commit();
}
private void showOffersFragment() {
Log.d(TAG, "OFFERS NULL OR :" + (offersFragment == null)+" ITEMS ="+items.size());
fm = getFragmentManager();
ft = fm.beginTransaction();
if (offersFragment == null) {
bundle = new Bundle();
bundle.putSerializable(ActivityConstants.OFFER_ITEMS, items);
offersFragment = new OffersFragment();
offersFragment.setArguments(bundle);
ft.add(R.id.main_frag_container, offersFragment,"offers");
} else {
ft.replace(R.id.main_frag_container, offersFragment,"offers");
}
ft.commit();
}
private void openMap() {
fm = getFragmentManager();
ft = fm.beginTransaction();
if(mapFragment==null){
mapFragment = new MapFragment();
ft.add(R.id.main_frag_container, mapFragment, "Map");
}else{
ft.replace(R.id.main_frag_container, mapFragment, "Map");
}
ft.commit();
mapFragment.getMapAsync(this);
}
现在问题是我在片段之间切换。它不会马上改变这些地方,所以它没有很好地回应。我应该在它们之间切换几次,以便片段出现。
有谁能告诉我如何优化/使其正常工作?
答案 0 :(得分:1)
它没有立即响应,因为一开始,一旦你选择了每个选项,这一行就会运行ft.add(R.id.main_frag_container, mapFragment, "Map");
,这意味着你要将新片段添加到同一个容器中而不是替换旧的片段。 / p>
使用ft.replace(R.id.main_frag_container, mapFragment, "Map");
代替ft.add(R.id.main_frag_container, mapFragment, "Map");
。虽然我可能错了,但容器(此处为R.id.main_fragment_container)必须已经添加了片段,一个选项是仅在容器为空时添加片段,否则替换。
如果您希望浏览以前的片段,可能需要检查addToBackStack。