fragment 跳转到另一个fragment中

时间:2021-12-12 08:55:23

要实现一个从Afragment中跳转到Bfragment中的例子

MainActivity.java

public class MainActivity extends AppCompatActivity {
BlankFragment2 blankFragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show();
}

private void show() {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
BlankFragment rightFragment = new BlankFragment();
transaction.add(R.id.fragmentlayout, rightFragment);
transaction.commit();
}
}

BlankFragment.java文件
public class BlankFragment extends Fragment {
public BlankFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_blank, container, false);
Button btu = (Button) v.findViewById(R.id.colick);
btu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity= (MainActivity) getActivity();
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
activity.blankFragment2 = new BlankFragment2();
ft.replace(R.id.fragmentlayout, activity.blankFragment2);
ft.commit();
}
});
return v;
}
}