private void setDefaultFragment() { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mFragmentOne = new FragmentOne(); mFragmentOne.setClickEnable(); transaction.replace(R.id.frameLayout_content, mFragmentOne); transaction.commit(); }
/** * Fragment常用的三个类 * * <p>android.app.Fragment 主要用于定义Fragment * * <p>android.app.FragmentManager 主要用于在Activity中操作Fragment * * <p>android.app.FragmentTransaction 保证一些列Fragment操作的原子性,熟悉事务这个词,一定能明白~ * * @param v */ @Override public void onClick(View v) { FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fgtransaction = fragmentManager.beginTransaction(); switch (v.getId()) { case R.id.btn_one: { if (mFragmentOne == null) { mFragmentOne = new FragmentOne(); mFragmentOne.setClickEnable(); } fgtransaction.replace(R.id.frameLayout_content, mFragmentOne); break; } case R.id.btn_two: { if (mFragmentTwo == null) { mFragmentTwo = new FragmentTwo(); mFragmentTwo.setClickEnable(); } fgtransaction.replace(R.id.frameLayout_content, mFragmentTwo); break; } // case R.id.btn_one: { // if (mFragmentTwo!=null){ // fgtransaction.hide(mFragmentTwo); // } // // if (mFragmentOne == null) { // mFragmentOne = new FragmentOne(); // mFragmentOne.setClickEnable(); // fgtransaction.add(R.id.frameLayout_content, mFragmentOne); // }else{ // fgtransaction.show(mFragmentOne); // } // break; // } // // case R.id.btn_two: { // // if (mFragmentOne!=null){ // fgtransaction.hide(mFragmentOne); // } // // if (mFragmentTwo == null) { // mFragmentTwo = new FragmentTwo(); // mFragmentTwo.setClickEnable(); // fgtransaction.add(R.id.frameLayout_content,mFragmentTwo); // }else{ // fgtransaction.show(mFragmentTwo); // } // break; // } default: { break; } } fgtransaction.commit(); }