在Android3.0以前,Android中一个界面里面如果包含多个界面切换,就必须用activity切换,在3.0之后,谷歌公司引入了Fragment,由于Fragment有自己的生命周期,使用方便,渐渐在很多场合都代替了activity。
如何在一个activity里面添加多个fragment切换,首先是xml的布局,xml的布局是一个Linearlayout跟一个framelayout组成,framelayout是显示fragment的,linearlayout里则是切换的导航,可以由按钮或者普通的布局将Linearlayout等分为几部分。
在src文件夹中先写好几个java文件,继承fragment类,然后在主activity中定义几个fragment,继承写好的java:
private DayFragment dayFragment;
private WeekFragment weekFragment;
private MonthFragment monthFragment;
定义一个tab,并写定为0,1,2;根据tab设置布局的颜色,字体的颜色以及将fragment增加到tab中,设置当前布局、字体颜色时,其他布局设置为其他的颜色,以便区分,最后记得commit();不然是不会呈现布局的 。
private void setTabSelection(int index) {
clearSelection();
FragmentTransaction transaction = fragmentManager.beginTransaction();
hideFragments(transaction);
switch (index) {
case 0:
dayLayout.setBackgroundColor(Color.parseColor("#6c7a81"));
weekLayout.setBackgroundColor(Color.parseColor("#1f262d"));
monthLayout.setBackgroundColor(Color.parseColor("#1f262d"));
dayText.setTextColor(Color.WHITE);
if (dayFragment == null) {
dayFragment = new DayFragment();
transaction.add(R.id.content, dayFragment);
} else {
transaction.show(dayFragment);
}
show(1);
break;
case 1:
weekLayout.setBackgroundColor(Color.parseColor("#6c7a81"));
monthLayout.setBackgroundColor(Color.parseColor("#1f262d"));
dayLayout.setBackgroundColor(Color.parseColor("#1f262d"));
weekText.setTextColor(Color.WHITE);
if (weekFragment == null) {
weekFragment = new WeekFragment();
transaction.add(R.id.content, weekFragment);
} else {
transaction.show(weekFragment);
}
show(2);
break;
case 2:
monthLayout.setBackgroundColor(Color.parseColor("#6c7a81"));
weekLayout.setBackgroundColor(Color.parseColor("#1f262d"));
dayLayout.setBackgroundColor(Color.parseColor("#1f262d"));
monthText.setTextColor(Color.WHITE);
if (monthFragment == null) {
monthFragment = new MonthFragment();
transaction.add(R.id.content, monthFragment);
} else {
transaction.show(monthFragment);
}
show(3);
break;
}
transaction.commit();
}
根据Linearlayout里面的布局的ID处理不同的点击事件,从而执行跳转到哪个Tab,达到切换Fragment的目的;
public void onClick(View v) {
switch (v.getId()) {
case R.id.message_layout:
setTabSelection(0);
break;
case R.id.contacts_layout:
setTabSelection(1);
break;
case R.id.news_layout:
setTabSelection(2);
break;
default:
break;
}
}
设置默认字体颜色:
private void clearSelection() {
dayText.setTextColor(Color.parseColor("#82858b"));
weekText.setTextColor(Color.parseColor("#82858b"));
monthText.setTextColor(Color.parseColor("#82858b"));
}
最后需要增加一个隐藏Fragment的函数,当切换Fragment的时候就隐藏当前的fragment,这就是fragment比activity好的原因,activity只能实例化跟销毁,而不像fragment一样可以隐藏。
private void hideFragments(FragmentTransaction transaction) {
if (dayFragment != null) {
transaction.hide(dayFragment);
}
if (weekFragment != null) {
transaction.hide(weekFragment);
}
if (monthFragment != null) {
transaction.hide(monthFragment);
}
}