Android利用Fragment实现Tab选项卡效果
利用Fragment实现Tab选项卡效果:
将RadioGroup与Fragment集合,实现tab选项卡效果,这里面最关键的几个文件:
1.FragmentTabAdapter类:
/** *@Description: *@Author:NateRobinson *@Since:2015-2-12 */ publicclassFragmentTabAdapterimplementsRadioGroup.OnCheckedChangeListener { privateList<Fragment>fragments;//一个tab页面对应一个Fragment privateRadioGrouprgs;//用于切换tab privateActivityactivity;//Fragment所属的Activity privateintfragmentContentId;//Activity中所要被替换的区域的id privateintcurrentTab;//当前Tab页面索引 privateOnRgsExtraCheckedChangedListeneronRgsExtraCheckedChangedListener;//用于让调用者在切换tab时候增加新的功能 publicFragmentTabAdapter(Activityactivity,List<Fragment>fragments,intfragmentContentId,RadioGrouprgs) { this.fragments=fragments; this.rgs=rgs; this.activity=activity; this.fragmentContentId=fragmentContentId; //默认显示第一页 android.app.FragmentTransactionft=activity.getFragmentManager().beginTransaction(); ft.add(fragmentContentId,fragments.get(0)); ft.commit(); rgs.setOnCheckedChangeListener(this); } @Override publicvoidonCheckedChanged(RadioGroupradioGroup,intcheckedId) { for(inti=0;i<rgs.getChildCount();i++) { if(rgs.getChildAt(i).getId()==(checkedId)) { Fragmentfragment=fragments.get(i); FragmentTransactionft=activity.getFragmentManager().beginTransaction(); getCurrentFragment().onPause();//暂停当前tab //getCurrentFragment().onStop();//暂停当前tab if(fragment.isAdded()) { //fragment.onStart();//启动目标tab的onStart() fragment.onResume();//启动目标tab的onResume() } else { ft.add(fragmentContentId,fragment); } showTab(i);//显示目标tab ft.commit(); //如果设置了切换tab额外功能功能接口 if(null!=onRgsExtraCheckedChangedListener) { onRgsExtraCheckedChangedListener.OnRgsExtraCheckedChanged(radioGroup,checkedId,i); } } } } /** *切换tab *@paramidx */ privatevoidshowTab(intidx) { for(inti=0;i<fragments.size();i++) { Fragmentfragment=fragments.get(i); FragmentTransactionft=activity.getFragmentManager().beginTransaction(); if(idx==i) { ft.show(fragment); } else { ft.hide(fragment); } ft.commit(); } currentTab=idx;//更新目标tab为当前tab } publicintgetCurrentTab() { returncurrentTab; } publicFragmentgetCurrentFragment() { returnfragments.get(currentTab); } publicOnRgsExtraCheckedChangedListenergetOnRgsExtraCheckedChangedListener() { returnonRgsExtraCheckedChangedListener; } publicvoidsetOnRgsExtraCheckedChangedListener(OnRgsExtraCheckedChangedListeneronRgsExtraCheckedChangedListener) { this.onRgsExtraCheckedChangedListener=onRgsExtraCheckedChangedListener; } /** *切换tab额外功能功能接口 */ publicinterfaceOnRgsExtraCheckedChangedListener { voidOnRgsExtraCheckedChanged(RadioGroupradioGroup,intcheckedId,intindex); } }
2.activity_main.xml布局文件:
<?xmlversion="1.0"encoding="UTF-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/tab_content" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1.0" android:background="#77557799"/> <RadioGroup android:id="@+id/tabs_rg" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" android:paddingBottom="7dp" android:paddingTop="7dp"> <RadioButton android:id="@+id/tab_rb_a" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" android:background="@drawable/selector_tab" android:button="@null" android:checked="true" android:drawableTop="@drawable/tablatestalert" android:gravity="center" android:singleLine="true" android:text="Tab1" android:textColor="#000000" android:textSize="13sp"/> <RadioButton android:id="@+id/tab_rb_b" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" android:background="@drawable/selector_tab" android:button="@null" android:drawableTop="@drawable/tabsearch" android:gravity="center" android:singleLine="true" android:text="Tab2" android:textColor="#000000" android:textSize="13sp"/> <RadioButton android:id="@+id/tab_rb_c" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1.0" android:background="@drawable/selector_tab" android:button="@null" android:drawableTop="@drawable/tabrecommd" android:gravity="center" android:singleLine="true" android:text="Tab3" android:textColor="#000000" android:textSize="13sp"/> </RadioGroup> </LinearLayout> </LinearLayout>
3.MainActivity类:
/** *@Description: *@Author:NateRobinson *@Since:2015-2-12 */ publicclassMainActivityextendsActivity { privateRadioGrouprgs; privateList<Fragment>fragments=newArrayList<Fragment>(); privateintindex; privatestaticBooleanisExit=false; privatestaticBooleanhasTask=false; privateRadioButtonbutton; privateTimertExit=newTimer(); privateTimerTasktask=newTimerTask() { @Override publicvoidrun() { isExit=false; hasTask=true; } }; privateFragmentTabAdaptertabAdapter; @Override publicvoidonCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragments.add(newFragmentOne()); fragments.add(newFragmentTwo()); fragments.add(newFragmentThree()); rgs=(RadioGroup)findViewById(R.id.tabs_rg); button=(RadioButton)findViewById(R.id.tab_rb_a); tabAdapter=newFragmentTabAdapter(this,fragments,R.id.tab_content,rgs); tabAdapter.setOnRgsExtraCheckedChangedListener(newFragmentTabAdapter.OnRgsExtraCheckedChangedListener() { @Override publicvoidOnRgsExtraCheckedChanged(RadioGroupradioGroup,intcheckedId,intindex) { //利用这个index可以实现,如果不是在主页,按第一遍让它先跳转到第一个Fragment System.out.println("Extra----"+index+"checked!!!"); MainActivity.this.index=index; } }); } @Override publicbooleanonKeyDown(intkeyCode,KeyEventevent) { if(keyCode==KeyEvent.KEYCODE_BACK) { if(index==0) { if(isExit==false) { isExit=true; Toast.makeText(MainActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show(); if(!hasTask) { tExit.schedule(task,1000); } } else { finish(); System.exit(0); } } else { //如果不是在主页,按第一遍让它先跳转到第一个Fragment //利用上面的check方法会导致onCheckedChanged方法被执行多次 //rgs.check(button.getId()); button.setChecked(true); } } returnfalse; } }
为了能同时学习Fragment生命周期,我在Fragment每个生命周期方法中加入了log打印,一个有三个这样的Fragment,我只贴出其中一个代码,其余和这个一样:
/** *@Description: *@Author:NateRobinson *@Since:2015-2-12 */ publicclassFragmentOneextendsBaseFragment { privateViewview; @Override publicvoidonAttach(Activityactivity) { super.onAttach(activity); Log.d(TAG,"1==>FragmentOne=>onAttach"); } @Override publicvoidonCreate(BundlesavedInstanceState) { Log.d(TAG,"2==>FragmentOne==>onCreate"); super.onCreate(savedInstanceState); } @Override publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState) { Log.d(TAG,"3==>FragmentOne==>onCreateView"); view=inflater.inflate(R.layout.fragment1,container,false); TextViewtv=(TextView)view.findViewById(R.id.tv); tv.setText("FragmentOne"); returnview; } @Override publicvoidonActivityCreated(BundlesavedInstanceState) { Log.d(TAG,"4==>FragmentOne==>onActivityCreated"); super.onActivityCreated(savedInstanceState); } @Override publicvoidonStart() { Log.d(TAG,"5==>FragmentOne==>onStart"); super.onStart(); } @Override publicvoidonResume() { Log.d(TAG,"6==>FragmentOne==>onResume"); super.onResume(); } @Override publicvoidonPause() { Log.d(TAG,"7==>FragmentOne==>onPause"); super.onPause(); } @Override publicvoidonStop() { Log.d(TAG,"8==>FragmentOne==>onStop"); super.onStop(); } @Override publicvoidonDestroyView() { Log.d(TAG,"9==>FragmentOne==>onDestroyView"); super.onDestroyView(); } @Override publicvoidonDestroy() { Log.d(TAG,"10==>FragmentOne==>onDestroy"); super.onDestroy(); } @Override publicvoidonDetach() { Log.d(TAG,"11==>FragmentOne==>onDetach"); super.onDetach(); } @Override publicvoidonViewCreated(Viewview,BundlesavedInstanceState) { Log.d(TAG,"FragmentOne==>onViewCreated"); super.onViewCreated(view,savedInstanceState); } }
在编写过程中,我为了实现如果不是在主页,按第一遍让它先跳转到第一个Fragment这个效果,一开始使用了rgs.check(button.getId());这个方法,结果发现,这样的话onCheckedChanged监听事件会执行两次,后来改为button.setChecked(true);这个方法之后,成功解决了这个问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。