Fragment动态实现导航栏
首先建立四个fragment_tem分别继承fragment,如下:
public class HalfyearFragment extends Fragment { public Context mContext=getActivity(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View myview =inflater.inflate(R.layout.examine_halfyearfragment,container,false); return myview; } }
HalfyearFragment继承了Fragment,并且绑定了xml。
然后在MainActivity中使用,就可以实现了。
@BindView(R.id.month_examine) Button monthExamine; @BindView(R.id.quarter_examine) Button quarterExamine; @BindView(R.id.Halfyear_examine) Button HalfyearExamine; @BindView(R.id.Oneyear_examine) Button OneyearExamine; private ArrayList<Fragment> fragments = new ArrayList<>(); private int position; private Fragment mContext; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.examine_main); ButterKnife.bind(this); initFragment(); initListener(); } private void initFragment() { fragments = new ArrayList<>(); fragments.add(new MonthFragment()); fragments.add(new QuaterFragment()); fragments.add(new HalfyearFragment()); fragments.add(new OneYearFragment()); } private void initListener() { examineGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.e_month: position = 0; break; case R.id.e_quarter: position = 1; break; case R.id.e_halfyear: position = 2; break; case R.id.e_year: position = 3; break; } Fragment baseFragment = getFragment(position); switchFragment(mContext, baseFragment); } }); examineGroup.check(R.id.e_month); } private Fragment getFragment(int position) { if (fragments != null && fragments.size() > 0) { Fragment baseFragment = fragments.get(position); return baseFragment; } return null; } private void switchFragment(Fragment formFragment, Fragment nextFragment) { if (mContext != nextFragment) { mContext = nextFragment; if (nextFragment != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); //判断nextFragment是否添加 if (!nextFragment.isAdded()) { //隐藏当前Fragment if (formFragment != null) { transaction.hide(formFragment); } transaction.add(R.id.content, nextFragment).commit(); } else { //隐藏当前Fragment if (formFragment != null) { transaction.hide(formFragment); } transaction.show(nextFragment).commit(); } } }
学习过程中参考了两个网站: