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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.