Android 介面(Fragment)切換
阿新 • • 發佈:2018-11-01
1.宣告
private FragmentManager fManager;//管理Fragment介面
2.初始化
fManager = getSupportFragmentManager();
3.切換程式碼
/** * Fragment切換 * * @param index */ private void setChoiceItem(int index) { FragmentTransaction transaction = fManager.beginTransaction(); clearChoice(); hideFragments(transaction); switch (index) { case 0: img_home.setBackgroundResource(R.drawable.home_select); if (home == null) { home = new HomeFragment(); transaction.add(R.id.main_frame_layout, home); } else { transaction.show(home); } break; case 1: img_message.setBackgroundResource(R.drawable.message_select); if (message == null) { message = new MessageFragment(); transaction.add(R.id.main_frame_layout, message); } else { transaction.show(message); } break; case 2: img_attention.setBackgroundResource(R.drawable.attention_select); if (attention == null) { attention = new AttentionFragment(); transaction.add(R.id.main_frame_layout, attention); } else { transaction.show(attention); } break; case 3: img_mine.setBackgroundResource(R.drawable.mine_select); if (mine == null) { mine = new MineFragment(); transaction.add(R.id.main_frame_layout, mine); } else { transaction.show(mine); } break; } transaction.commit(); }
4.隱藏
/** * 隱藏片段 * * @param transaction */ private void hideFragments(FragmentTransaction transaction) { if (home != null) { transaction.hide(home); } if (message != null) { transaction.hide(message); } if (attention != null) { transaction.hide(attention); } if (mine != null) { transaction.hide(mine); } }
5.清除選中樣式
/** * 清除選中Fragment的樣式 */ public void clearChoice() { img_home.setBackgroundResource(R.drawable.home_unselect); img_message.setBackgroundResource(R.drawable.message_unselect); img_attention.setBackgroundResource(R.drawable.attention_unselect); img_mine.setBackgroundResource(R.drawable.mine_unselect); }