Android Programming Experience-use Actionbar+fragment+viewpager to dynamically switch menu effects

Source: Internet
Author: User

1. First up




2. The effect of this example is mainly applicable to the current page when there are more than one page, when the fragment switch, you can use different menu styles and the content in the current fragment to cooperate, can greatly increase the reusability, see, below I would like to introduce my main steps to achieve this effect

2.1 Because I have 3 styles here, I need to create three files under the Res/menu folder, Style1.xml,style2.xml,style3.xml. Here I take style1.xml as an example, the specific text icon file can be as required, Style2.xml,style3.xml similar.

Style1.xml source code is as follows:

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >    <item        android:id= "@+id/ Action_item1 "        android:orderincategory=" "        android:showasaction=" Ifroom|withtext "      android:icon=" @ Drawable/ic_menu_discard "        android:title=" @string/style1 "/></menu>



2.2 Under the Res/layout file to create the corresponding view file of activity and fragment, I take activity with one of the fragment example, the rest of you can extrapolate

Activity_main.xml Source

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">         <android.support.v4.view.viewpager        android:id=" @+id/viewpager "        android: Layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_gravity= "center" >    </android.support.v4.view.ViewPager>    </RelativeLayout>

Fragment_first Source

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Fill_ Parent "    android:layout_height=" fill_parent "    android:orientation=" vertical "><textview     Android : layout_width= "fill_parent"    android:layout_height= "wrap_content"    android:text= "first fragment"    /> </RelativeLayout>

2.3 Next is the logical implementation, according to the effect I need to create a main logic activity and three fragment logical files, here I only take a fragment example, the remaining two similar

Firstfragment Source:

Package Com.yqc.menuswitchdemo;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class FirstFragment Extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle Savedinstancestate) {View Rootview = inflater.inflate (R.layout.fragment_first, Container,false); return rootView;}}


Where you need a custom adapter when using fragment, the source code is as follows:

Package Com.yqc.menuswitchdemo;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmentpageradapter;public Class Lffragmentpageradapter extends Fragmentpageradapter {fragment[] fragmentarray;public lffragmentpageradapter ( Fragmentmanager fm,fragment[] fragmentArray2) {super (FM);//TODO auto-generated constructor stubif (null = = FragmentArray2) {This.fragmentarray = new fragment[] {};} else {this.fragmentarray = FragmentArray2;}} @Overridepublic Fragment getItem (int arg0) {//TODO auto-generated method Stubreturn fragmentarray[arg0];} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn fragmentarray.length;}}



Finally, Mainactivity Source:

Package Com.yqc.menuswitchdemo;import Android.os.bundle;import Android.app.actionbar;import Android.app.actionbar.tab;import Android.support.v4.app.fragment;import android.support.v4.app.FragmentActivity; Import Android.support.v4.view.viewpager;import Android.support.v4.view.viewpager.onpagechangelistener;import Android.view.menu;import android.view.menuinflater;import android.view.menuitem;import android.widget.Toast;/** * @ Author Yangqicong Yang Chizun QQ Group 90733929 Welcome Exchange */public Class Mainactivity extends Fragmentactivity {private Viewpager viewpager; Private ActionBar ActionBar; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Viewpager = (Viewpager) Findviewbyid (R.id.viewpager); Fragment fragment1 = new Firstfragment (); Fragment Fragment2 = new Secondfragment (); Fragment Fragment3 = new Thirdfragment (); fragment[] Fragmentarray = new fragment[] {fragment1, fragment2,fragment3}; Lffragmentpageradapter adapter = New Lffragmentpageradapter (Getsupportfragmentmanager (), Fragmentarray); Viewpager.setadapter (adapter); Viewpager.setoffscreenpagelimit (3); Viewpager.setonpagechangelistener (new Onpagechangelistener () {@Overridepublic void onpageselected (int arg0) {//TODO auto-generated method StubSystem.out.println ("arg0:" + arg0); Actionbar.setselectednavigationitem (arg0);} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {//TODO auto-generated method stub} @Overridepublic vo ID onpagescrollstatechanged (int arg0) {//TODO auto-generated Method stub}}); ActionBar = Getactionbar ();//Set ActionBar Mode: Tab navigation Actionbar.setnavigationmode (actionbar.navigation_mode_tabs);//Actionbar.gettab TAB1 = Actionbar.newtab () . SetText ("tab 1"). SetIcon (Android. R.drawable.ic_menu_agenda). Settablistener (New Actiontablistener (fragment1)); tab TAB2 = Actionbar.newtab (). SetText ("tab 2"). SetIcon (Android. R.drawable.ic_menu_agenda). Settablistener (New Actiontablistener (Fragment2)); tab TAB3 = Actionbar.newtab (). SetText ("Tab 3 "). SetIcon (Android. R.drawable.ic_menu_agenda). Settablistener (New Actiontablistener (FRAGMENT3)); Actionbar.addtab (TAB1); Actionbar.addtab (TAB2); Actionbar.addtab (TAB3);} Class Actiontablistener implements Actionbar.tablistener {//Declaration fragmentprivate Fragment fragment;// By constructing a reference to the corresponding Fragmentpublic Actiontablistener (Fragment Fragment) {this.fragment = Fragment;} @Overridepublic void ontabreselected (Tab tab, android.app.FragmentTransaction ft) {//TODO auto-generated method stub}@ overridepublic void ontabselected (Tab tab, android.app.FragmentTransaction ft) {//TODO auto-generated method stub//ft.a DD (Android. R.id.content, fragment, null); mtype = Tab.getposition (); System.out.println ("Tab.getposition ():" + tab.getposition ()); Viewpager.setcurrentitem (Tab.getposition ()); Invalidateoptionsmenu ();} @Overridepublic void ontabunselected (Tab tab, android.app.FragmentTransaction ft) {//TODO auto-generated method stub}}@ Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; this adds ITEMs to the Action bar if it is present.getmenuinflater (). Inflate (R.menu.style1, menu); return true;} private int mtype; @Overridepublic boolean onprepareoptionsmenu (Menu menu) {//TODO auto-generated method StubSystem.out.println ("Current mtype:" + mtype); Menu.clear (); Menuinflater inflater = this.getmenuinflater (), switch (mtype) {case 0:inflater.inflate (r.menu.style1, menu); Case 1:inflater.inflate (r.menu.style2, menu), Break;case 2:inflater.inflate (R.menu.style3, menu); return Super.onprepareoptionsmenu (menu);} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//TODO auto-generated method Stubswitch (Item.getitemid ( ) {Case R.id.action_item1:toast.maketext (this, "clicked the first button", Toast.length_short). Show (); Break;case r.id.action_item2 : Toast.maketext (This, "clicked the second button", Toast.length_short). Show (); Break;case R.id.action_item3:toast.maketext (This, " Click on the Third button ", Toast.length_short). Show (); break;} return super.onoptionsitemselected (item);}}


3. It is important to note that my mtype is a mainactivity in the main logic, which is used to identify the current fragment and then switch, and if you have any questions, you are welcome to communicate.

This example of all the source code click here, reproduced please indicate the source, thank you!




Android Programming Experience-use Actionbar+fragment+viewpager to dynamically switch menu effects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.