Reputation: 27
How to click and add another Fragment in one Fragment?
There is a button click to add Fragment in one Activity. There is another button in firstFragment. I want to click the button and add secondFragment. How to realize this?
Thanks in advance!
Upvotes: 0
Views: 611
Reputation: 272
In Fragment1, inflate an XML layout with a button. Set the button's onClickListener and define an onClick method.
// In Fragment1...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layoutWithButton, container, false);
Button b = (Button) view.findViewById(R.id.myButton);
b.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layoutWithButton:
Fragment fragment2 = new Fragment2;
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment2); // where container is the FrameLayout where Fragment 1 was first placed
transaction.commit();
break;
default:
break;
}
Depending on how you want to handle your back stack, you can include transaction.addToBackStack(null);
as needed.
Upvotes: 2