Транзакция не удаляет представления, которые уже существуют в контейнере, который будет использоваться для транзакции. Чтобы удалить эти представления, вам нужно обернуть начальное содержимое ParentFragment
как фрагмент и заменить его дочерним фрагментом (с транзакцией replace
, а не с транзакцией add
). Я внес некоторые изменения в ваш код, проверьте это ниже:
Родительский фрагмент:
public class ParentFragment extends Fragment {
private static final int CONTAINER_ID = 0x2222;
private static final String INITIAL_FRAG = "initial_fragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FrameLayout wrapper = new FrameLayout(getActivity());
wrapper.setId(CONTAINER_ID);
// look for our two possible fragments, if we don't find the
// InitialContentFragment add it
if (getChildFragmentManager().findFragmentByTag(INITIAL_FRAG) == null) {
InitialContentFragment initContent = new InitialContentFragment();
Bundle args = new Bundle();
args.putString("text",
"I'm the initial content fragment in the parent fragment");
initContent.setArguments(args);
getChildFragmentManager().beginTransaction()
.add(CONTAINER_ID, initContent, INITIAL_FRAG).commit();
}
return wrapper;
}
public void requestFragmentTransaction() {
FragmentTransaction fragmentTransaction = getChildFragmentManager()
.beginTransaction();
ChildFragment childFragment = new ChildFragment();
Bundle args = new Bundle();
args.putString("text", "Hi I am Child Fragment");
childFragment.setArguments(args);
fragmentTransaction.replace(CONTAINER_ID, childFragment, "ChildFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
где InitialContentFragment
:
public static class InitialContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate the layout file that would normally be in the
// ParentFragment at start
View view = inflater.inflate(R.layout.layout_parentfragment,
container, false);
Bundle bundle = getArguments();
final String text = bundle.getString("text");
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText(text);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ParentFragment parent = (ParentFragment) InitialContentFragment.this
.getParentFragment();
parent.requestFragmentTransaction();
}
});
return view;
}
}
В качестве примечания: НИКОГДА не игнорируйте блок try-catch, как это делали вы.
person
user
schedule
10.07.2013