tab swipe tab, comprehensive viewpager+fragment+ custom Tab+actionbar content

Source: Internet
Author: User
Tags getcolor

1.

The second menu tab1,tab2,tab3 is a reference to the online example, the first menu is based on its change.

2. Menu

The menu here is implemented in two ways, one through the layout file and one through the custom component LinearLayout. Custom only needs to pass in the name of the menu, listen to the event when switching. The following is a viewpager+fragment implementation that changes the tab selection when sliding.

Custom tab Bottom line is used translateanimation animation to achieve scrolling, layout file using Viewpager method onpagescrolled and onpagescrollstatechanged to achieve.

2.1 Custom LinearLayout

<span style= "FONT-SIZE:14PX;" >package Com.example.actionbar;import Java.util.list;import Android.annotation.suppresslint;import Android.content.context;import Android.graphics.color;import Android.util.attributeset;import Android.util.displaymetrics;import Android.view.gravity;import Android.view.view;import Android.view.animation.accelerateinterpolator;import Android.view.animation.animation;import Android.view.animation.animation.animationlistener;import Android.view.animation.translateanimation;import Android.widget.linearlayout;import Android.widget.textview;public class Tabview extends LinearLayout {private int scre    Enwidth;    Private string[] tabnames;    private int fontSize;    Private textview[] mtextviews;    private int linehight;    Private View Sliderline;    private int tabwidth;    private int selectedpage;        Public Tabview (Context context) {super (context);    Init (context); } public Tabview (context context, string[] Tabnames, displaymetricsdisplaymetrics, int fontSize) {super (context);        This.tabnames = Tabnames;        ScreenWidth = Displaymetrics.widthpixels;        This.fontsize = fontSize;    Init (context); } public Tabview (context context, list<string> names, displaymetrics displaymetrics, int fontSize) {Super        (context);            if (names! = null) {tabnames = new string[names.size ()];            for (int i = 0; i < tabnames.length; i++) {This.tabnames[i] = Names.get (i);        }} screenwidth = Displaymetrics.widthpixels;        This.fontsize = fontSize;    Init (context);        } public Tabview (context context, AttributeSet Attrs) {Super (context, attrs);    Init (context); } @SuppressLint ("Newapi") public Tabview (context context, AttributeSet attrs, int defstyle) {Super (context,        Attrs, Defstyle);    Init (context); } private void Init (context context) {if (Tabnames==null | | tabnames.leNgth = = 0) {return;        } linehight = (int) getresources (). Getdimension (R.dimen.cursor_height);        Tabwidth = Screenwidth/tabnames.length;        Mtextviews = new Textview[tabnames.length];        SetOrientation (linearlayout.vertical); Linearlayout.layoutparams layoutparams = new Linearlayout.layoutparams (New Layoutparams (SCREENWIDTH/TABN        Ames.length, layoutparams.match_parent));        LinearLayout linearlayout = new LinearLayout (context);        int height = (int) getresources (). Getdimension (R.dimen.tab_height);        Linearlayout.setlayoutparams (New Layoutparams (layoutparams.match_parent,height));        Linearlayout.setorientation (linearlayout.horizontal);            for (int i = 0; i < tabnames.length; i++) {TextView TextView = new TextView (context);            Textview.settext (Tabnames[i] + "");            Textview.setlayoutparams (Layoutparams);       Textview.settextsize (fontSize);     Textview.settextcolor (Color.Black);            Textview.setgravity (Gravity.center);            Mtextviews[i] = TextView;            Final int pos = i;                    Textview.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {                    if (Selectedpage!=pos) {Ishidden (POS);                    } if (Tabviewlistener! = null) {Tabviewlistener.currentpos (POS);            }                }            });        Linearlayout.addview (TextView);        } addview (LinearLayout); if (tabnames.length>1) {linearlayout.layoutparams linelayoutparams = new Linearlayout.layoutparams (TabWidth, Li        Nehight);        TextView TextView = new TextView (context);        Textview.setbackgroundcolor (Color.parsecolor ("#FA8653"));        Textview.setlayoutparams (Linelayoutparams);        Sliderline=textview; AddView (TextView); } IshidDen (0);    } private Tabviewlistener Tabviewlistener;    public void Settabviewlistener (Tabviewlistener linlistener) {this.tabviewlistener = Linlistener;    } public Tabviewlistener Gettabviewlistener () {return tabviewlistener;    } public interface Tabviewlistener {public void currentpos (int pos);        }/* * Toggle Font Color */public void Ishidden (int pos) {if (pos >= 0 | | pos < tabnames.length) {            Tabscroll (POS);            Mtextviews[selectedpage].settextcolor (Color.Black);            Mtextviews[pos].settextcolor (Color.parsecolor ("#FA8653"));        Selectedpage=pos;    }/* * scrolling animation */private void Tabscroll (int index) {if (Selectedpage==index) {return;} Sliderline.settranslationx (0); translateanimation animation = new Translateanimation (selectedpage* tabwidth, index * tabwidth, 0, 0); Animation.setinterpolator (New Accelerateinterpolator ()); animation.setduration (+); Animation.setfillenabled ( True; Animation.setfillafter (true); sliderline.startanimation (animation); Animation.setanimationlistener (new Animationlistener () {@Overridepublic void Onanimationstart (Animation Animation) {} @Overridepublic void Onanimationrepeat (Animation Animation) {} @Overridepublic void Onanimationend (Animation Animation) {    Sliderline.clearanimation (); Sliderline.settranslationx (Selectedpage * tabwidth);}); }}</span>
2.2 Using layout files

<span style= "FONT-SIZE:14PX;" >package Com.example.actionbar;import Java.util.arraylist;import Android.app.activity;import Android.content.context;import Android.support.v4.app.fragment;import android.support.v4.app.FragmentActivity; Import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmentpageradapter;import Android.support.v4.view.viewpager;import Android.util.attributeset;import Android.util.displaymetrics;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.view.animation.accelerateinterpolator;import Android.view.animation.animation;import Android.view.animation.animation.animationlistener;import Android.view.animation.translateanimation;import Android.widget.linearlayout;import Android.widget.TextView; public class Tabfragmentindicator extends LinearLayout Implementsviewpager.onpagechangelistener, Onclicklistener { Ontabclicklistener Ontabclicklistener; Context Mcontext; Viewpager Mviewpager;  View Container;private view slider;private int tabnum;private int selectedpage = 0;private int preselectedpage = 0;private int scrollstate;private final int scroll_state_press = 1;private final int scroll_state_up = 2;private float UNITWIDTH;PR Ivate float Currentpositionpix;private Boolean isclick = false; Sectionspageradapter msectionspageradapter;private arraylist<class<?>> fragmentList = new ArrayList< Class<?>> ();p ublic tabfragmentindicator (context context, AttributeSet Attrs) {Super (context, attrs); Mcontext = context;} public void Setviewpager (Viewpager viewpager) {viewpager.setoffscreenpagelimit (3); mviewpager = Viewpager; Mviewpager.setonpagechangelistener (this); msectionspageradapter = new Sectionspageradapter ((FragmentActivity) Mcontext). Getsupportfragmentmanager ()); Mviewpager.setadapter (Msectionspageradapter);} /** * Add Fragment * * @param index * @param claz */public void addfragment (int index, class<?> claz) {FragmentliSt.add (index, Claz); if (msectionspageradapter! = null) msectionspageradapter.notifydatasetchanged (); /** * Set Tab layout * * @param layoutid */public void settabcontainerview (int layoutid) {container = Layoutinflater.from (mconte XT). Inflate (LayoutID, null), This.addview (container, 0); int height = (int) getresources (). Getdimension (r.dimen.tab_ height); Viewgroup.layoutparams params = Container.getlayoutparams ();p arams.height = Height;container.setlayoutparams (params if (container instanceof viewgroup) {tabnum = ((ViewGroup) container). Getchildcount (); for (int i = 0; i < tabnum; i++ {(ViewGroup) container). Getchildat (i). Settag (i);((viewgroup) container). Getchildat (i). Setonclicklistener (This) ;}}} /** * Set Underline * * @param layoutid */public void settabsliderview (int layoutid) {slider = Layoutinflater.from (mcontext). infl ATE (LayoutID, null); This.addview (slider, 1); Setcursorwidth ();} Public View Getindicatorview () {return container;} public class Sectionspageradapter extends Fragmentpageradapter {PublIC Sectionspageradapter (fragmentmanager FM) {super (FM);} @Overridepublic Fragment getItem (int index) {return fragment.instantiate (Mcontext, Fragmentlist.get (index). GetName () , null);} @Overridepublic int GetCount () {return fragmentlist.size ();}} @Overridepublic void onpageselected (int position) {((TextView) ((ViewGroup) container). Getchildat (Selectedpage)). SetTextColor (This.getresources (). GetColor (Android. R.color.black));((TextView) ((ViewGroup) container). Getchildat (position)). SetTextColor (This.getresources (). GetColor (R.color.orange)); selectedpage = position;} @Overridepublic void onpagescrolled (int position, float positionoffset,int positionoffsetpixels) {//Not click tab option if (! Isclick && Positionoffsetpixels! = 0) {if (scrollstate = = scroll_state_press) {//Finger pressed state if (selectedpage = = Posit ION) {//= left pull, corresponding tab goes right Slider.settranslationx (currentpositionpix+ positionoffsetpixels/tabnum);} else {// means to the right pull Slider.settranslationx (currentpositionpix-(Unitwidth-positionoffsetpixels/tabnum));}} else if (scrollstate = = scroll_state_up) {//Finger lifted State System.out.println ("preselectedpage---" + preselectedpage + "Positio N---"+ position+" offset "+positionoffsetpixels); if (preselectedpage = = position) {//Pull left Slider.settranslationx ( Currentpositionpix + positionoffsetpixels/tabnum);} else {//= to right-pull Slider.settranslationx (Currentpositionpix-(Unitwidth-positionoffsetpixels/tabnum));}}}} There are three states for this parameter (0,1,2). state//==1 When the time implied is sliding, state==2 the hour of the tacit slide is finished, state==0 of the hour implied nothing did. @Overridepublic void onpagescrollstatechanged (int state) {System.out.println ("onpagescrollstatechanged------State" + state), if (!isclick) {Currentpositionpix = Selectedpage * unitwidth;scrollstate = State;preselectedpage = SelectedPage; }}/** * * Move underline when you click the tab page */@Overridepublic void OnClick (View v) {Final int index = (Integer) v.gettag (); Ontabclicklistener. Ontabclick (v); if (selectedpage = = index) {return;} Isclick = True;slider.settranslationx (0); translateanimation animation = new Translateanimation (selectedpage* Unitwidth, Index * unitwidth, 0, 0); Animation.setinterpolator (new Accelerateinterpolator ()); Animation.setduration ( Animation.setfillenabled (True); Animation.setfillafter (true); slider.startanimation (animation); Animation.setanimationlistener (New Animationlistener () {@Overridepublic void Onanimationstart (animation animation) { Mviewpager.setcurrentitem (index, True);} @Overridepublic void Onanimationrepeat (Animation Animation) {} @Overridepublic void Onanimationend (Animation Animation {slider.clearanimation (); Slider.settranslationx (Selectedpage * unitwidth); Isclick = false;}});}  /** sets the width of the cursor and gets the moving unit length of float **/private void setcursorwidth () {int cursorwidth = Getwindowwidth ()/tabnum;unitwidth = (float) getwindowwidth ()/Tabnum;int cursorheight = (int) getresources (). Getdimension (R.dimen.cursor_height); Viewgroup.layoutparams params = Slider.getlayoutparams ();p arams.height = Cursorheight;params.width = CursorWidth; Slider.setlayoutparams (params);} /** get screen width **/private int GetwindowwidtH () {displaymetrics dm = new Displaymetrics ();((Activity) mcontext). Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); return dm.widthpixels;} public void Setontabclicklistener (Ontabclicklistener ontabclicklistener) {This.ontabclicklistener = Ontabclicklistener;} Public interface Ontabclicklistener {public void Ontabclick (View v);}} </span>

<span style= "FONT-SIZE:14PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:gravity=" Center_ver Tical "android:orientation=" horizontal "> <textview android:id=" @+id/tab1_text "Android:layout_w Idth= "0DP" android:layout_weight= "1.0" android:gravity= "center" android:layout_height= "@dimen/tab_hei  Ght "android:textcolor=" @color/orange "style=" @style/style.actionbartabtextstyle "android:text=" Tab1 " /> <textview android:id= "@+id/tab2_text" android:layout_width= "0DP" android:layout_height= " @dimen/tab_height "android:layout_weight=" 1.0 "android:gravity=" center "style=" @style/style.actionbar Tabtextstyle "android:text=" tab2 "/> <textview android:id=" @+id/tab3_text "Android:layout_wi Bt.= "0DP" android:layout_height= "@dimen/tab_height" android:layout_weight= "1.0" android:gravity= "center" style= "@style/style.actionbartabtextstyle" android:text= "Tab3"/></linearlayout></span>
3. Test Call

<span style= "font-family: ' Comic Sans MS ';" ><span style= "FONT-SIZE:14PX;" >public class Homeactivity extends Fragmentactivity Implementsontabclicklistener, Oncategoryselectedlistener { Private Viewpager mviewpager;private tabfragmentindicator tabfragmentindicator;private View categoryTab;private Categorywindow categorywindow;private settingmenuwindow menuwindow;private linearlayout ll_tab;private TabView Tabview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_home); Menuwindow = new Settingmenuwindow (this); Mviewpager = (Viewpager) Findviewbyid (r.id.viewpager); ll_tab = (linearlayout) Findviewbyid (r.id.ll_tab); tabfragmentindicator = ( Tabfragmentindicator) Findviewbyid (r.id.tabfragmentindicator); tabfragmentindicator.addfragment (0, Countingfragment.class); Tabfragmentindicator.addfragment (1, Countingfragment.class); Tabfragmentindicator.addfragment (2, countingfragment.class); tabfragmentindicator.settabcOntainerview (R.layout.layout_home_tabindicator); Tabfragmentindicator.settabsliderview (R.layout.layout_home_tab _slider); Tabfragmentindicator.setontabclicklistener (this); Tabfragmentindicator.setviewpager (MViewPager); Categorywindow = new Categorywindow (this);D isplaymetrics dm = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM) Tabview = new Tabview (this, new string[] {"Menu", "Discovery", "Settings"},DM, "Ll_tab.addview"); Abview); Tabview.settabviewlistener (new Tabviewlistener () {@Overridepublic void currentpos (int pos) {Tabview.ishidden (POS);}});} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;} public boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.menu_more: Menuwindow.showasdropdown (Findviewbyid (R.id.anchorview), 1800, -25); return super.onoptionsitemselected (item);} @Overridepublic void Ontabclick (View v) {int pos = (Integer) v.gettag (); if (pos = = 0) {CategorywinDow.showasdropdown (Tabfragmentindicator,-20, 0);} Tabview.gettabviewlistener (). Currentpos (POS);} @Overridepublic void oncategoryselected (string name, string id) {((TextView) categorytab). SetText (name); Categorywindow.dismiss ();}} </span></span>

SOURCE download


tab swipe tab, comprehensive viewpager+fragment+ custom Tab+actionbar content

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.