对于导航栏(RadioButton+Fragment)点击返回Fragment时重新加载数据的现象,进行了优化,给用户流畅的体验
xml代码:
<RadioGroup
android:layout_alignParentBottom="true"
android:id="@+id/footer_menu_radiogroup"
android:layout_width="match_parent"
android:layout_height="59dp"
android:orientation="horizontal"
android:gravity="center_vertical">
<RadioButton
android:id="@+id/footer_query"
android:text="首页"
style="@style/radioStyle"
android:checked="true"
android:drawableTop="@drawable/current_selector"/>
<RadioButton
android:id="@+id/footer_search"
android:text="搜索"
style="@style/radioStyle"
android:drawableTop="@drawable/bottom_search"/>
<RadioButton
android:id="@+id/footer_current"
android:text="实时"
style="@style/radioStyle"
android:drawableTop="@drawable/query_selector"/>
<RadioButton
android:id="@+id/footer_my"
android:text="我"
style="@style/radioStyle"
android:drawableTop="@drawable/current_my"/>
</RadioGroup>
Java代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initRadioGroup();
}
private void initData() {
HomePageFragment homePageFragment=new HomePageFragment();
SearchFragment searchFragment=new SearchFragment();
CurrentFragment currentFragment=new CurrentFragment();
MyFragment myFragment=new MyFragment();
fragments.add(homePageFragment);
fragments.add(searchFragment);
fragments.add(currentFragment);
fragments.add(myFragment);
//默认显示第一个Fragment
getSupportFragmentManager().beginTransaction().add(R.id.main_content,homePageFragment).commit();
private void initRadioGroup() {
tv = ((TextView) findViewById(R.id.title_text));
footer_menu_radiogroup = (RadioGroup)findViewById(R.id.footer_menu_radiogroup);
footer_menu_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.footer_current:
changeFragment(2);
tv.setText("实时");
break;
case R.id.footer_query:
changeFragment(0);
tv.setText("首页");
break;
case R.id.footer_search:
changeFragment(1);
tv.setText("搜索");
break;
case R.id.footer_my:
changeFragment(3);
tv.setText("我");
break;
}
}
});
}
private void changeFragment(int i) {
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
Fragment targetFragment=fragments.get(i);
Fragment positionFragment=fragments.get(position);
if(targetFragment.isAdded()){
transaction.show(targetFragment).hide(positionFragment).commit();
}else{
transaction.add(R.id.main_content,targetFragment).hide(positionFragment).commit();
}
position=i;
}