Android Navigation TabBar控件实现多彩标签栏
程序员文章站
2024-03-03 15:35:28
先看看效果图:
源码下载:android navigation tabbar控件实现多彩标签栏
代码:
mainactivity.java
packag...
先看看效果图:
源码下载:android navigation tabbar控件实现多彩标签栏
代码:
mainactivity.java
package com.bzu.gxs.meunguide; import android.app.activity; import android.graphics.color; import android.support.v4.view.pageradapter; import android.support.v4.view.viewpager; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.textview; import java.util.arraylist; public class mainactivity extends activity{ @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); initui(); } private void initui() { final viewpager viewpager = (viewpager) findviewbyid(r.id.vp_horizontal_ntb); viewpager.setadapter(new pageradapter() { @override public int getcount() { return 5; } @override public boolean isviewfromobject(view view, object object) { return view.equals(object); } @override public void destroyitem(final view container,final int position,final object object) { ((viewpager)container).removeview((view)object); } @override public object instantiateitem(final viewgroup container,final int position) { final view view = layoutinflater.from(getbasecontext()).inflate(r.layout.activity_item,null,false); final textview textview = (textview) view.findviewbyid(r.id.txt_vp_item_page); textview.settext(string.format("界面 %d",position)); container.addview(view); return view; } }); // final string[] colors = getresources().getstringarray(r.array.default_preview); final navigationtabbar navigationtabbar = (navigationtabbar) findviewbyid(r.id.ntb_horizontal); final arraylist<navigationtabbar.model> models = new arraylist<>(); models.add(new navigationtabbar.model( getresources().getdrawable(r.drawable.ic_first), color.parsecolor(colors[0]),"one")); models.add(new navigationtabbar.model( getresources().getdrawable(r.drawable.ic_second),color.parsecolor(colors[1]),"two")); models.add(new navigationtabbar.model( getresources().getdrawable(r.drawable.ic_third),color.parsecolor(colors[2]),"thirt")); models.add(new navigationtabbar.model( getresources().getdrawable(r.drawable.ic_fourth),color.parsecolor(colors[3]),"fourth")); models.add(new navigationtabbar.model( getresources().getdrawable(r.drawable.ic_fifth),color.parsecolor(colors[4]),"fifth")); navigationtabbar.setmodels(models); navigationtabbar.setviewpager(viewpager,2); navigationtabbar.setonpagechangelistener(new viewpager.onpagechangelistener() { @override public void onpagescrolled(final int position, final float positionoffset, final int positionoffsetpixels) { } @override public void onpageselected(final int position) { navigationtabbar.getmodels().get(position).hidebadge(); } @override public void onpagescrollstatechanged(final int state) { } }); navigationtabbar.post(new runnable() { @override public void run() { final view bgnavigationtabar = findviewbyid(r.id.bg_ntb_horizontal); bgnavigationtabar.getlayoutparams().height = (int) navigationtabbar.getheight(); } }); navigationtabbar.postdelayed(new runnable() { @override public void run() { for (int i=0; i<navigationtabbar.getmodels().size() ; i++){ final navigationtabbar.model model = navigationtabbar.getmodels().get(i); switch (i){ case 0: model.setbadgetitle("gxs1"); break; case 1: model.setbadgetitle("gxs2"); break; case 2: model.setbadgetitle("gxs3"); break; case 3: model.setbadgetitle("gxs4"); break; case 4: model.setbadgetitle("gxs5"); break; default: break; } navigationtabbar.postdelayed(new runnable() { @override public void run() { model.showbadge(); } },i * 100); } } },500); } }
navigationtabbar.java
package com.bzu.gxs.meunguide; import android.animation.animator; import android.animation.valueanimator; import android.content.context; import android.content.res.configuration; import android.content.res.typedarray; import android.graphics.bitmap; import android.graphics.canvas; import android.graphics.color; import android.graphics.matrix; import android.graphics.paint; import android.graphics.porterduff; import android.graphics.porterduffcolorfilter; import android.graphics.porterduffxfermode; import android.graphics.rect; import android.graphics.rectf; import android.graphics.typeface; import android.graphics.drawable.bitmapdrawable; import android.graphics.drawable.drawable; import android.os.parcel; import android.os.parcelable; import android.support.v4.view.viewpager; import android.text.textpaint; import android.text.textutils; import android.util.attributeset; import android.view.motionevent; import android.view.view; import android.view.animation.acceleratedecelerateinterpolator; import android.view.animation.accelerateinterpolator; import android.view.animation.decelerateinterpolator; import android.view.animation.interpolator; import android.view.animation.linearinterpolator; import android.widget.scroller; import java.lang.reflect.field; import java.util.arraylist; import java.util.list; import java.util.random; /** * created by gxs on 2016/5/7. */ public class navigationtabbar extends view implements viewpager.onpagechangelistener { // ntp constants private final static string preview_badge = "0"; private final static string preview_title = "title"; private final static int invalid_index = -1; private final static int default_badge_animation_duration = 200; private final static int default_badge_refresh_animation_duration = 100; private final static int default_animation_duration = 300; private final static int default_inactive_color = color.parsecolor("#9f90af"); private final static int default_active_color = color.white; private final static float min_fraction = 0.0f; private final static float non_scaled_fraction = 0.35f; private final static float max_fraction = 1.0f; private final static int min_alpha = 0; private final static int max_alpha = 255; private final static float active_icon_scale_by = 0.3f; private final static float icon_size_fraction = 0.45f; private final static float title_active_icon_scale_by = 0.2f; private final static float title_icon_size_fraction = 0.45f; private final static float title_active_scale_by = 0.2f; private final static float title_size_fraction = 0.2f; private final static float title_margin_fraction = 0.15f; private final static float badge_horizontal_fraction = 0.5f; private final static float badge_vertical_fraction = 0.75f; private final static float badge_title_size_fraction = 0.85f; private final static int all_index = 0; private final static int active_index = 1; private final static int left_index = 0; private final static int center_index = 1; private final static int right_index = 2; private final static int top_index = 0; private final static int bottom_index = 1; private final static float left_fraction = 0.25f; private final static float center_fraction = 0.5f; private final static float right_fraction = 0.75f; private final static interpolator decelerate_interpolator = new decelerateinterpolator(); private final static interpolator accelerate_interpolator = new accelerateinterpolator(); // ntp and pointer bounds private final rectf mbounds = new rectf(); private final rectf mpointerbounds = new rectf(); // badge bounds and bg badge bounds private final rect mbadgebounds = new rect(); private final rectf mbgbadgebounds = new rectf(); // canvas, where all of other canvas will be merged private bitmap mbitmap; private canvas mcanvas; // canvas with icons private bitmap miconsbitmap; private canvas miconscanvas; // canvas for our rect pointer private bitmap mpointerbitmap; private canvas mpointercanvas; // main paint private final paint mpaint = new paint(paint.anti_alias_flag) { { setdither(true); setstyle(style.fill); } }; // pointer paint private final paint mpointerpaint = new paint(paint.anti_alias_flag) { { setdither(true); setxfermode(new porterduffxfermode(porterduff.mode.dst_in)); } }; // icons paint private final paint miconpaint = new paint(paint.anti_alias_flag) { { setdither(true); } }; // paint for icon mask pointer private final paint miconpointerpaint = new paint(paint.anti_alias_flag) { { setstyle(style.fill); setxfermode(new porterduffxfermode(porterduff.mode.src_in)); } }; // paint for model title private final paint mmodeltitlepaint = new textpaint(paint.anti_alias_flag) { { setdither(true); setcolor(color.white); settextalign(align.center); } }; // paint for badge private final paint mbadgepaint = new textpaint(paint.anti_alias_flag) { { setdither(true); settextalign(align.center); setfakeboldtext(true); } }; // variables for animator private final valueanimator manimator = new valueanimator(); private final resizeinterpolator mresizeinterpolator = new resizeinterpolator(); private int manimationduration; // ntp models private list<model> mmodels = new arraylist<>(); // variables for viewpager private viewpager mviewpager; private viewpager.onpagechangelistener monpagechangelistener; private int mscrollstate; // tab listener private ontabbarselectedindexlistener montabbarselectedindexlistener; private valueanimator.animatorlistener manimatorlistener; // variables for sizes private float mmodelsize; private int miconsize; // corners radius for rect mode private float mcornersradius; // model title size and margin private float mmodeltitlesize; private float mtitlemargin; // model badge title size and margin private float mbadgemargin; private float mbadgetitlesize; // model title mode: active ar all private titlemode mtitlemode; // model badge position: left, center or right private badgeposition mbadgeposition; // model badge gravity: top or bottom private badgegravity mbadgegravity; // indexes private int mlastindex = invalid_index; private int mindex = invalid_index; // general fraction value private float mfraction; // coordinates of pointer private float mstartpointerx; private float mendpointerx; private float mpointerlefttop; private float mpointerrightbottom; // detect if model has title private boolean mistitled; // detect if model has badge private boolean misbadged; // detect if model icon scaled private boolean misscaled; // detect if model badge have custom typeface private boolean misbadgeusetypeface; // detect if is bar mode or indicator pager mode private boolean misviewpagermode; // detect whether the horizontal orientation private boolean mishorizontalorientation; // detect if we move from left to right private boolean misresizein; // detect if we get action down event private boolean misactiondown; // detect if we get action down event on pointer private boolean mispointeractiondown; // detect when we set index from tab bar nor from viewpager private boolean missetindexfromtabbar; // color variables private int minactivecolor; private int mactivecolor; // custom typeface private typeface mtypeface; public navigationtabbar(final context context) { this(context, null); } public navigationtabbar(final context context, final attributeset attrs) { this(context, attrs, 0); } public navigationtabbar(final context context, final attributeset attrs, final int defstyleattr) { super(context, attrs, defstyleattr); //init ntb // always draw setwillnotdraw(false); // more speed! setlayertype(layer_type_hardware, null); final typedarray typedarray = context.obtainstyledattributes(attrs, r.styleable.navigationtabbar); try { setistitled( typedarray.getboolean(r.styleable.navigationtabbar_ntb_titled, false) ); setisbadged( typedarray.getboolean(r.styleable.navigationtabbar_ntb_badged, false) ); setisscaled( typedarray.getboolean(r.styleable.navigationtabbar_ntb_scaled, true) ); setisbadgeusetypeface( typedarray.getboolean(r.styleable.navigationtabbar_ntb_badge_use_typeface, false) ); settitlemode( typedarray.getint(r.styleable.navigationtabbar_ntb_title_mode, all_index) ); setbadgeposition( typedarray.getint(r.styleable.navigationtabbar_ntb_badge_position, right_index) ); setbadgegravity( typedarray.getint(r.styleable.navigationtabbar_ntb_badge_gravity, top_index) ); settypeface( typedarray.getstring(r.styleable.navigationtabbar_ntb_typeface) ); setinactivecolor( typedarray.getcolor( r.styleable.navigationtabbar_ntb_inactive_color, default_inactive_color ) ); setactivecolor( typedarray.getcolor( r.styleable.navigationtabbar_ntb_active_color, default_active_color ) ); setanimationduration( typedarray.getinteger( r.styleable.navigationtabbar_ntb_animation_duration, default_animation_duration ) ); setcornersradius( typedarray.getdimension(r.styleable.navigationtabbar_ntb_corners_radius, 0.0f) ); // init animator manimator.setfloatvalues(min_fraction, max_fraction); manimator.setinterpolator(new linearinterpolator()); manimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(final valueanimator animation) { updateindicatorposition((float) animation.getanimatedvalue()); } }); // set preview models if (isineditmode()) { // get preview colors string[] previewcolors = null; try { final int previewcolorsid = typedarray.getresourceid( r.styleable.navigationtabbar_ntb_preview_colors, 0 ); previewcolors = previewcolorsid == 0 ? null : typedarray.getresources().getstringarray(previewcolorsid); } catch (exception exception) { previewcolors = null; exception.printstacktrace(); } finally { if (previewcolors == null) previewcolors = typedarray.getresources().getstringarray(r.array.default_preview); for (string previewcolor : previewcolors) mmodels.add(new model(null, color.parsecolor(previewcolor))); requestlayout(); } } } finally { typedarray.recycle(); } } public int getanimationduration() { return manimationduration; } public void setanimationduration(final int animationduration) { manimationduration = animationduration; manimator.setduration(manimationduration); resetscroller(); } public list<model> getmodels() { return mmodels; } public void setmodels(final list<model> models) { //set update listeners to badge model animation for (final model model : models) { model.mbadgeanimator.removeallupdatelisteners(); model.mbadgeanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { @override public void onanimationupdate(final valueanimator animation) { model.mbadgefraction = (float) animation.getanimatedvalue(); postinvalidate(); } }); } mmodels.clear(); mmodels = models; requestlayout(); } public boolean istitled() { return mistitled; } public void setistitled(final boolean istitled) { mistitled = istitled; requestlayout(); } public boolean isbadged() { return misbadged; } public void setisbadged(final boolean isbadged) { misbadged = isbadged; requestlayout(); } public boolean isscaled() { return misscaled; } public void setisscaled(final boolean isscaled) { misscaled = isscaled; requestlayout(); } public boolean isbadgeusetypeface() { return misbadgeusetypeface; } public void setisbadgeusetypeface(final boolean isbadgeusetypeface) { misbadgeusetypeface = isbadgeusetypeface; setbadgetypeface(); postinvalidate(); } public titlemode gettitlemode() { return mtitlemode; } private void settitlemode(final int index) { switch (index) { case active_index: settitlemode(titlemode.active); break; case all_index: default: settitlemode(titlemode.all); } } public void settitlemode(final titlemode titlemode) { mtitlemode = titlemode; postinvalidate(); } public badgeposition getbadgeposition() { return mbadgeposition; } private void setbadgeposition(final int index) { switch (index) { case left_index: setbadgeposition(badgeposition.left); break; case center_index: setbadgeposition(badgeposition.center); break; case right_index: default: setbadgeposition(badgeposition.right); } } public void setbadgeposition(final badgeposition badgeposition) { mbadgeposition = badgeposition; postinvalidate(); } public badgegravity getbadgegravity() { return mbadgegravity; } private void setbadgegravity(final int index) { switch (index) { case bottom_index: setbadgegravity(badgegravity.bottom); break; case top_index: default: setbadgegravity(badgegravity.top); } } public void setbadgegravity(final badgegravity badgegravity) { mbadgegravity = badgegravity; requestlayout(); } public typeface gettypeface() { return mtypeface; } public void settypeface(final string typeface) { typeface temptypeface; try { temptypeface = typeface.createfromasset(getcontext().getassets(), typeface); } catch (exception e) { temptypeface = typeface.create(typeface.default, typeface.normal); e.printstacktrace(); } settypeface(temptypeface); } public void settypeface(final typeface typeface) { mtypeface = typeface; mmodeltitlepaint.settypeface(typeface); setbadgetypeface(); postinvalidate(); } private void setbadgetypeface() { mbadgepaint.settypeface( misbadgeusetypeface ? mtypeface : typeface.create(typeface.default, typeface.normal) ); } public int getactivecolor() { return mactivecolor; } public void setactivecolor(final int activecolor) { mactivecolor = activecolor; miconpointerpaint.setcolor(activecolor); postinvalidate(); } public int getinactivecolor() { return minactivecolor; } public void setinactivecolor(final int inactivecolor) { minactivecolor = inactivecolor; // set color filter to wrap icons with inactive color miconpaint.setcolorfilter(new porterduffcolorfilter(inactivecolor, porterduff.mode.src_in)); mmodeltitlepaint.setcolor(minactivecolor); postinvalidate(); } public float getcornersradius() { return mcornersradius; } public void setcornersradius(final float cornersradius) { mcornersradius = cornersradius; postinvalidate(); } public float getbadgemargin() { return mbadgemargin; } public float getbarheight() { return mbounds.height(); } public ontabbarselectedindexlistener getontabbarselectedindexlistener() { return montabbarselectedindexlistener; } // set on tab bar selected index listener where you can trigger action onstart or onend public void setontabbarselectedindexlistener(final ontabbarselectedindexlistener ontabbarselectedindexlistener) { montabbarselectedindexlistener = ontabbarselectedindexlistener; if (manimatorlistener == null) manimatorlistener = new animator.animatorlistener() { @override public void onanimationstart(final animator animation) { if (montabbarselectedindexlistener != null) montabbarselectedindexlistener.onstarttabselected(mmodels.get(mindex), mindex); } @override public void onanimationend(final animator animation) { if (montabbarselectedindexlistener != null) montabbarselectedindexlistener.onendtabselected(mmodels.get(mindex), mindex); } @override public void onanimationcancel(final animator animation) { } @override public void onanimationrepeat(final animator animation) { } }; manimator.removelistener(manimatorlistener); manimator.addlistener(manimatorlistener); } public void setviewpager(final viewpager viewpager) { // detect whether viewpager mode if (viewpager == null) { misviewpagermode = false; return; } if (mviewpager == viewpager) return; if (mviewpager != null) mviewpager.setonpagechangelistener(null); if (viewpager.getadapter() == null) throw new illegalstateexception("viewpager does not provide adapter instance."); misviewpagermode = true; mviewpager = viewpager; mviewpager.addonpagechangelistener(this); resetscroller(); postinvalidate(); } public void setviewpager(final viewpager viewpager, int index) { setviewpager(viewpager); mindex = index; if (misviewpagermode) mviewpager.setcurrentitem(index, true); postinvalidate(); } // reset scroller and reset scroll duration equals to animation duration private void resetscroller() { if (mviewpager == null) return; try { final field scrollerfield = viewpager.class.getdeclaredfield("mscroller"); scrollerfield.setaccessible(true); final resizeviewpagerscroller scroller = new resizeviewpagerscroller(getcontext()); scrollerfield.set(mviewpager, scroller); } catch (exception e) { e.printstacktrace(); } } public void setonpagechangelistener(final viewpager.onpagechangelistener listener) { monpagechangelistener = listener; } public int getmodelindex() { return mindex; } public void setmodelindex(int index) { setmodelindex(index, false); } // set model index from touch or programmatically public void setmodelindex(int index, boolean force) { if (manimator.isrunning()) return; if (mmodels.isempty()) return; // this check gives us opportunity to have an non selected model if (mindex == invalid_index) force = true; // detect if last is the same if (index == mindex) return; // snap index to models size index = math.max(0, math.min(index, mmodels.size() - 1)); misresizein = index < mindex; mlastindex = mindex; mindex = index; missetindexfromtabbar = true; if (misviewpagermode) { if (mviewpager == null) throw new illegalstateexception("viewpager is null."); mviewpager.setcurrentitem(index, true); } // set startx and endx for animation, where we animate two sides of rect with different interpolation mstartpointerx = mpointerlefttop; mendpointerx = mindex * mmodelsize; // if it force, so update immediately, else animate // this happens if we set index oncreate or something like this // you can use force param or call this method in some post() if (force) updateindicatorposition(max_fraction); else manimator.start(); } private void updateindicatorposition(final float fraction) { // update general fraction mfraction = fraction; // set the pointer left top side coordinate mpointerlefttop = mstartpointerx + (mresizeinterpolator.getresizeinterpolation(fraction, misresizein) * (mendpointerx - mstartpointerx)); // set the pointer right bottom side coordinate mpointerrightbottom = (mstartpointerx + mmodelsize) + (mresizeinterpolator.getresizeinterpolation(fraction, !misresizein) * (mendpointerx - mstartpointerx)); // update pointer postinvalidate(); } // update ntp private void notifydatasetchanged() { postinvalidate(); } @override public boolean ontouchevent(final motionevent event) { // return if animation is running if (manimator.isrunning()) return true; // if is not idle state, return if (mscrollstate != viewpager.scroll_state_idle) return true; switch (event.getaction()) { case motionevent.action_down: // action down touch misactiondown = true; if (!misviewpagermode) break; // detect if we touch down on pointer, later to move if (mishorizontalorientation) mispointeractiondown = (int) (event.getx() / mmodelsize) == mindex; else mispointeractiondown = (int) (event.gety() / mmodelsize) == mindex; break; case motionevent.action_move: // if pointer touched, so move if (mispointeractiondown) { if (mishorizontalorientation) mviewpager.setcurrentitem((int) (event.getx() / mmodelsize), true); else mviewpager.setcurrentitem((int) (event.gety() / mmodelsize), true); break; } if (misactiondown) break; case motionevent.action_up: // press up and set model index relative to current coordinate if (misactiondown) { if (mishorizontalorientation) setmodelindex((int) (event.getx() / mmodelsize)); else setmodelindex((int) (event.gety() / mmodelsize)); } case motionevent.action_cancel: case motionevent.action_outside: default: // reset action touch variables mispointeractiondown = false; misactiondown = false; break; } return true; } @override protected void onmeasure(final int widthmeasurespec, final int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); // get measure size final int width = measurespec.getsize(widthmeasurespec); final int height = measurespec.getsize(heightmeasurespec); if (mmodels.isempty() || width == 0 || height == 0) return; // detect orientation and calculate icon size if (width > height) { mishorizontalorientation = true; // get smaller side float side = mmodelsize > height ? height : mmodelsize; if (misbadged) side -= side * title_size_fraction; mmodelsize = (float) width / (float) mmodels.size(); miconsize = (int) (side * (mistitled ? title_icon_size_fraction : icon_size_fraction)); mmodeltitlesize = side * title_size_fraction; mtitlemargin = side * title_margin_fraction; // if is badged mode, so get vars and set paint with default bounds if (misbadged) { mbadgetitlesize = mmodeltitlesize * badge_title_size_fraction; final rect badgebounds = new rect(); mbadgepaint.settextsize(mbadgetitlesize); mbadgepaint.gettextbounds(preview_badge, 0, 1, badgebounds); mbadgemargin = (badgebounds.height() * 0.5f) + (mbadgetitlesize * badge_horizontal_fraction * badge_vertical_fraction); } } else { mishorizontalorientation = false; mistitled = false; misbadged = false; mmodelsize = (float) height / (float) mmodels.size(); miconsize = (int) ((mmodelsize > width ? width : mmodelsize) * icon_size_fraction); } // set bounds for ntb mbounds.set(0.0f, 0.0f, width, height - mbadgemargin); // set main bitmap mbitmap = bitmap.createbitmap(width, height, bitmap.config.argb_8888); mcanvas = new canvas(mbitmap); // set pointer canvas mpointerbitmap = bitmap.createbitmap(width, height, bitmap.config.argb_8888); mpointercanvas = new canvas(mpointerbitmap); // set icons canvas miconsbitmap = bitmap.createbitmap(width, height, bitmap.config.argb_8888); miconscanvas = new canvas(miconsbitmap); // set scale fraction for icons for (model model : mmodels) { final float originaliconsize = model.micon.getwidth() > model.micon.getheight() ? model.micon.getwidth() : model.micon.getheight(); model.minactiveiconscale = (float) miconsize / originaliconsize; model.mactiveiconscaleby = model.minactiveiconscale * (mistitled ? title_active_icon_scale_by : active_icon_scale_by); } // set start position of pointer for preview or on start if (isineditmode() || !misviewpagermode) { missetindexfromtabbar = true; // set random in preview mode if (isineditmode()) { mindex = new random().nextint(mmodels.size()); if (misbadged) for (int i = 0; i < mmodels.size(); i++) { final model model = mmodels.get(i); if (i == mindex) { model.mbadgefraction = max_fraction; model.showbadge(); } else { model.mbadgefraction = min_fraction; model.hidebadge(); } } } mstartpointerx = mindex * mmodelsize; mendpointerx = mstartpointerx; updateindicatorposition(max_fraction); } } @override protected void ondraw(final canvas canvas) { if (mcanvas == null || mpointercanvas == null || miconscanvas == null) return; // reset and clear canvases mcanvas.drawcolor(0, porterduff.mode.clear); mpointercanvas.drawcolor(0, porterduff.mode.clear); miconscanvas.drawcolor(0, porterduff.mode.clear); // get pointer badge margin for gravity final float pointerbadgemargin = mbadgegravity == badgegravity.top ? mbadgemargin : 0.0f; // draw our model colors for (int i = 0; i < mmodels.size(); i++) { mpaint.setcolor(mmodels.get(i).getcolor()); if (mishorizontalorientation) { final float left = mmodelsize * i; final float right = left + mmodelsize; mcanvas.drawrect( left, pointerbadgemargin, right, mbounds.height() + pointerbadgemargin, mpaint ); } else { final float top = mmodelsize * i; final float bottom = top + mmodelsize; mcanvas.drawrect(0.0f, top, mbounds.width(), bottom, mpaint); } } // set bound of pointer if (mishorizontalorientation) mpointerbounds.set( mpointerlefttop, pointerbadgemargin, mpointerrightbottom, mbounds.height() + pointerbadgemargin ); else mpointerbounds.set(0.0f, mpointerlefttop, mbounds.width(), mpointerrightbottom); // draw pointer for model colors if (mcornersradius == 0) mpointercanvas.drawrect(mpointerbounds, mpaint); else mpointercanvas.drawroundrect(mpointerbounds, mcornersradius, mcornersradius, mpaint); // draw pointer into main canvas mcanvas.drawbitmap(mpointerbitmap, 0.0f, 0.0f, mpointerpaint); // draw model icons for (int i = 0; i < mmodels.size(); i++) { final model model = mmodels.get(i); // variables to center our icons final float leftoffset; final float topoffset; final float matrixcenterx; final float matrixcentery; // set vars for icon when model with title or without final float iconmargintitleheight = miconsize + mtitlemargin + mmodeltitlesize; final float lefttitleoffset = (mmodelsize * i) + (mmodelsize * 0.5f); final float toptitleoffset = mbounds.height() - (mbounds.height() - iconmargintitleheight) * 0.5f; if (mishorizontalorientation) { leftoffset = (mmodelsize * i) + (mmodelsize - model.micon.getwidth()) * 0.5f; topoffset = (mbounds.height() - model.micon.getheight()) * 0.5f; matrixcenterx = leftoffset + model.micon.getwidth() * 0.5f; matrixcentery = topoffset + model.micon.getheight() * 0.5f + (mistitled && mtitlemode == titlemode.all ? mtitlemargin * 0.5f : 0.0f); } else { leftoffset = (mbounds.width() - model.micon.getwidth()) * 0.5f; topoffset = (mmodelsize * i) + (mmodelsize - model.micon.getheight()) * 0.5f; matrixcenterx = leftoffset + model.micon.getwidth() * 0.5f; matrixcentery = topoffset + model.micon.getheight() * 0.5f; } // title translate position final float titletranslate = -model.micon.getheight() + toptitleoffset - mtitlemargin * 0.5f; // translate icon to model center model.miconmatrix.settranslate( leftoffset, (mistitled && mtitlemode == titlemode.all) ? titletranslate : topoffset ); // get interpolated fraction for left last and current models final float interpolation = mresizeinterpolator.getresizeinterpolation(mfraction, true); final float lastinterpolation = mresizeinterpolator.getresizeinterpolation(mfraction, false); // final float interpolation = // misscaled ? mresizeinterpolator.getresizeinterpolation(mfraction, true); // final float lastinterpolation = // misscaled ? mresizeinterpolator.getresizeinterpolation(mfraction, false) : // (max_fraction - non_scaled_fraction); // scale value relative to interpolation final float matrixscale = model.mactiveiconscaleby * (misscaled ? interpolation : non_scaled_fraction); final float matrixlastscale = model.mactiveiconscaleby * (misscaled ? lastinterpolation : (max_fraction - non_scaled_fraction)); // get title alpha relative to interpolation final int titlealpha = (int) (max_alpha * interpolation); final int titlelastalpha = max_alpha - (int) (max_alpha * lastinterpolation); // get title scale relative to interpolation final float titlescale = max_fraction + ((misscaled ? interpolation : non_scaled_fraction) * title_active_scale_by); final float titlelastscale = misscaled ? (max_fraction + title_active_scale_by) - (lastinterpolation * title_active_scale_by) : titlescale; // check if we handle models from touch on ntp or from viewpager // there is a strange logic of viewpager onpagescrolled method, so it is if (missetindexfromtabbar) { if (mindex == i) updatecurrentmodel( model, leftoffset, topoffset, titletranslate, interpolation, matrixcenterx, matrixcentery, matrixscale, titlescale, titlealpha ); else if (mlastindex == i) updatelastmodel( model, leftoffset, topoffset, titletranslate, lastinterpolation, matrixcenterx, matrixcentery, matrixlastscale, titlelastscale, titlelastalpha ); else updateinactivemodel( model, leftoffset, topoffset, titlescale, matrixscale, matrixcenterx, matrixcentery ); } else { if (i != mindex && i != mindex + 1) updateinactivemodel( model, leftoffset, topoffset, titlescale, matrixscale, matrixcenterx, matrixcentery ); else if (i == mindex + 1) updatecurrentmodel( model, leftoffset, topoffset, titletranslate, interpolation, matrixcenterx, matrixcentery, matrixscale, titlescale, titlealpha ); else if (i == mindex) updatelastmodel( model, leftoffset, topoffset, titletranslate, lastinterpolation, matrixcenterx, matrixcentery, matrixlastscale, titlelastscale, titlelastalpha ); } // draw model icon miconscanvas.drawbitmap(model.micon, model.miconmatrix, miconpaint); if (mistitled) miconscanvas.drawtext( isineditmode() ? preview_title : model.gettitle(), lefttitleoffset, toptitleoffset, mmodeltitlepaint ); } // draw pointer with active color to wrap out active icon if (mcornersradius == 0) miconscanvas.drawrect(mpointerbounds, miconpointerpaint); else miconscanvas.drawroundrect(mpointerbounds, mcornersradius, mcornersradius, miconpointerpaint); // draw general bitmap canvas.drawbitmap(mbitmap, 0.0f, 0.0f, null); // draw icons bitmap on top canvas.drawbitmap(miconsbitmap, 0.0f, pointerbadgemargin, null); // if is not badged, exit if (!misbadged) return; // model badge margin and offset relative to gravity mode final float modelbadgemargin = mbadgegravity == badgegravity.top ? mbadgemargin : mbounds.height(); final float modelbadgeoffset = mbadgegravity == badgegravity.top ? 0.0f : mbounds.height() - mbadgemargin; for (int i = 0; i < mmodels.size(); i++) { final model model = mmodels.get(i); // set preview badge title if (isineditmode() || textutils.isempty(model.getbadgetitle())) model.setbadgetitle(preview_badge); // set badge title bounds mbadgepaint.settextsize(mbadgetitlesize * model.mbadgefraction); mbadgepaint.gettextbounds( model.getbadgetitle(), 0, model.getbadgetitle().length(), mbadgebounds ); // get horizontal and vertical padding for bg final float horizontalpadding = mbadgetitlesize * badge_horizontal_fraction; final float verticalpadding = horizontalpadding * badge_vertical_fraction; // set horizontal badge offset final float badgeboundshorizontaloffset = (mmodelsize * i) + (mmodelsize * mbadgeposition.mpositionfraction); // if is badge title only one char, so create circle else round rect if (model.getbadgetitle().length() == 1) { final float badgemargin = mbadgemargin * model.mbadgefraction; mbgbadgebounds.set( badgeboundshorizontaloffset - badgemargin, modelbadgemargin - badgemargin, badgeboundshorizontaloffset + badgemargin, modelbadgemargin + badgemargin ); } else mbgbadgebounds.set( badgeboundshorizontaloffset - mbadgebounds.centerx() - horizontalpadding, modelbadgemargin - (mbadgemargin * model.mbadgefraction), badgeboundshorizontaloffset + mbadgebounds.centerx() + horizontalpadding, modelbadgeoffset + (verticalpadding * 2.0f) + mbadgebounds.height() ); // set color and alpha for badge bg if (model.mbadgefraction == min_fraction) mbadgepaint.setcolor(color.transparent); else mbadgepaint.setcolor(mactivecolor); mbadgepaint.setalpha((int) (max_alpha * model.mbadgefraction)); // set corners to round rect for badge bg and draw final float cornerradius = mbgbadgebounds.height() * 0.5f; canvas.drawroundrect(mbgbadgebounds, cornerradius, cornerradius, mbadgepaint); // set color and alpha for badge title if (model.mbadgefraction == min_fraction) mbadgepaint.setcolor(color.transparent); else mbadgepaint.setcolor(model.getcolor()); mbadgepaint.setalpha((int) (max_alpha * model.mbadgefraction)); // set badge title center position and draw title final float badgehalfheight = mbadgebounds.height() * 0.5f; float badgeverticaloffset = (mbgbadgebounds.height() * 0.5f) + badgehalfheight - mbadgebounds.bottom + modelbadgeoffset; canvas.drawtext( model.getbadgetitle(), badgeboundshorizontaloffset, badgeverticaloffset + mbadgebounds.height() - (mbadgebounds.height() * model.mbadgefraction), mbadgepaint ); } } // method to transform current fraction of ntb and position private void updatecurrentmodel( final model model, final float leftoffset, final float topoffset, final float titletranslate, final float interpolation, final float matrixcenterx, final float matrixcentery, final float matrixscale, final float textscale, final int textalpha ) { if (mistitled && mtitlemode == titlemode.active) model.miconmatrix.settranslate( leftoffset, topoffset - (interpolation * (topoffset - titletranslate)) ); model.miconmatrix.postscale( model.minactiveiconscale + matrixscale, model.minactiveiconscale + matrixscale, matrixcenterx, matrixcentery + (mistitled && mtitlemode == titlemode.active ? mtitlemargin * 0.5f * interpolation : 0.0f) ); mmodeltitlepaint.settextsize(mmodeltitlesize * textscale); if (mtitlemode == titlemode.active) mmodeltitlepaint.setalpha(textalpha); } // method to transform last fraction of ntb and position private void updatelastmodel( final model model, final float leftoffset, final float topoffset, final float titletranslate, final float lastinterpolation, final float matrixcenterx, final float matrixcentery, final float matrixlastscale, final float textlastscale, final int textlastalpha ) { if (mistitled && mtitlemode == titlemode.active) model.miconmatrix.settranslate( leftoffset, titletranslate + (lastinterpolation * (topoffset - titletranslate)) ); model.miconmatrix.postscale( model.minactiveiconscale + model.mactiveiconscaleby - matrixlastscale, model.minactiveiconscale + model.mactiveiconscaleby - matrixlastscale, matrixcenterx, matrixcentery + (mistitled && mtitlemode == titlemode.active ? mtitlemargin * 0.5f - (mtitlemargin * 0.5f * lastinterpolation) : 0.0f) ); mmodeltitlepaint.settextsize(mmodeltitlesize * textlastscale); if (mtitlemode == titlemode.active) mmodeltitlepaint.setalpha(textlastalpha); } // method to transform others fraction of ntb and position private void updateinactivemodel( final model model, final float leftoffset, final float topoffset, final float textscale, final float matrixscale, final float matrixcenterx, final float matrixcentery ) { if (mistitled && mtitlemode == titlemode.active) model.miconmatrix.settranslate(leftoffset, topoffset); if (misscaled) model.miconmatrix.postscale( model.minactiveiconscale, model.minactiveiconscale, matrixcenterx, matrixcentery ); else model.miconmatrix.postscale( model.minactiveiconscale + matrixscale, model.minactiveiconscale + matrixscale, matrixcenterx, matrixcentery ); mmodeltitlepaint.settextsize(mmodeltitlesize * (misscaled ? 1.0f : textscale)); if (mtitlemode == titlemode.active) mmodeltitlepaint.setalpha(min_alpha); } @override public void onpagescrolled(int position, float positionoffset, final int positionoffsetpixels) { // if we animate, don`t call this if (!missetindexfromtabbar) { misresizein = position < mindex; mlastindex = mindex; mindex = position; mstartpointerx = position * mmodelsize; mendpointerx = mstartpointerx + mmodelsize; updateindicatorposition(positionoffset); } if (monpagechangelistener != null) monpagechangelistener.onpagescrolled(position, positionoffset, positionoffsetpixels); } @override public void onpageselected(final int position) { // if vp idle, so update if (mscrollstate == viewpager.scroll_state_idle) { misresizein = position < mindex; mlastindex = mindex; mindex = position; postinvalidate(); } } @override public void onpagescrollstatechanged(final int state) { // if vp idle, reset to min_fraction if (state == viewpager.scroll_state_idle) { mfraction = min_fraction; missetindexfromtabbar = false; if (monpagechangelistener != null) monpagechangelistener.onpageselected(mindex); else { if (montabbarselectedindexlistener != null) montabbarselectedindexlistener.onendtabselected(mmodels.get(mindex), mindex); } } mscrollstate = state; if (monpagechangelistener != null) monpagechangelistener.onpagescrollstatechanged(state); } @override public void onrestoreinstancestate(parcelable state) { final savedstate savedstate = (savedstate) state; super.onrestoreinstancestate(savedstate.getsuperstate()); mindex = savedstate.index; requestlayout(); } @override public parcelable onsaveinstancestate() { final parcelable superstate = super.onsaveinstancestate(); final savedstate savedstate = new savedstate(superstate); savedstate.index = mindex; return savedstate; } private static class savedstate extends basesavedstate { int index; public savedstate(parcelable superstate) { super(superstate); } private savedstate(parcel in) { super(in); index = in.readint(); } @override public void writetoparcel(parcel dest, int flags) { super.writetoparcel(dest, flags); dest.writeint(index); } @suppresswarnings("unuseddeclaration") public static final creator<savedstate> creator = new creator<savedstate>() { @override public savedstate createfromparcel(parcel in) { return new savedstate(in); } @override public savedstate[] newarray(int size) { return new savedstate[size]; } }; } @override protected void onconfigurationchanged(final configuration newconfig) { // config view on rotate etc. super.onconfigurationchanged(newconfig); requestlayout(); // refresh pointer and state after config changed to current final int tempindex = mindex; setmodelindex(invalid_index, true); post(new runnable() { @override public void run() { setmodelindex(tempindex, true); } }); } // model class public static class model { private string mtitle = ""; private int mcolor; private bitmap micon; private final matrix miconmatrix = new matrix(); private string mbadgetitle = ""; private string mtempbadgetitle = ""; private float mbadgefraction; private boolean misbadgeshowed; private boolean misbadgeupdated; private final valueanimator mbadgeanimator = new valueanimator(); private float minactiveiconscale; private float mactiveiconscaleby; public model(final drawable icon, final int color) { mcolor = color; if (icon != null) { if (icon instanceof bitmapdrawable) micon = ((bitmapdrawable) icon).getbitmap(); else { micon = bitmap.createbitmap( icon.getintrinsicwidth(), icon.getintrinsicheight(), bitmap.config.argb_8888 ); final canvas canvas = new canvas(micon); icon.setbounds(0, 0, canvas.getwidth(), canvas.getheight()); icon.draw(canvas); } } else { micon = bitmap.createbitmap(1, 1, bitmap.config.rgb_565); } mbadgeanimator.addlistener(new animator.animatorlistener() { @override public void onanimationstart(final animator animation) { } @override public void onanimationend(final animator animation) { // detect whether we just update text and don`t reset show state if (!misbadgeupdated) misbadgeshowed = !misbadgeshowed; else misbadgeupdated = false; } @override public void onanimationcancel(final animator animation) { } @override public void onanimationrepeat(final animator animation) { // change title when we update and don`t see the title if (misbadgeupdated) mbadgetitle = mtempbadgetitle; } }); } public model(final drawable icon, final int color, final string title) { this(icon, color); mtitle = title; } public model(final drawable icon, final int color, final string title, final string badgetitle) { this(icon, color, title); mbadgetitle = badgetitle; } public string gettitle() { return mtitle; } public void settitle(final string title) { mtitle = title; } public int getcolor() { return mcolor; } public void setcolor(final int color) { mcolor = color; } public boolean isbadgeshowed() { return misbadgeshowed; } public string getbadgetitle() { return mbadgetitle; } public void setbadgetitle(final string badgetitle) { mbadgetitle = badgetitle; } // if your badge is visible on screen, so you can update title with animation public void updatebadgetitle(final string badgetitle) { if (!misbadgeshowed) return; if (mbadgeanimator.isrunning()) mbadgeanimator.end(); mtempbadgetitle = badgetitle; misbadgeupdated = true; mbadgeanimator.setfloatvalues(max_fraction, min_fraction); mbadgeanimator.setduration(default_badge_refresh_animation_duration); mbadgeanimator.setrepeatmode(valueanimator.reverse); mbadgeanimator.setrepeatcount(1); mbadgeanimator.start(); } public void togglebadge() { if (mbadgeanimator.isrunning()) mbadgeanimator.end(); if (misbadgeshowed) hidebadge(); else showbadge(); } public void showbadge() { misbadgeupdated = false; if (mbadgeanimator.isrunning()) mbadgeanimator.end(); if (misbadgeshowed) return; mbadgeanimator.setfloatvalues(min_fraction, max_fraction); mbadgeanimator.setinterpolator(decelerate_interpolator); mbadgeanimator.setduration(default_badge_animation_duration); mbadgeanimator.setrepeatmode(valueanimator.restart); mbadgeanimator.setrepeatcount(0); mbadgeanimator.start(); } public void hidebadge() { misbadgeupdated = false; if (mbadgeanimator.isrunning()) mbadgeanimator.end(); if (!misbadgeshowed) return; mbadgeanimator.setfloatvalues(max_fraction, min_fraction); mbadgeanimator.setinterpolator(accelerate_interpolator); mbadgeanimator.setduration(default_badge_animation_duration); mbadgeanimator.setrepeatmode(valueanimator.restart); mbadgeanimator.setrepeatcount(0); mbadgeanimator.start(); } } // custom scroller with custom scroll duration private class resizeviewpagerscroller extends scroller { public resizeviewpagerscroller(context context) { super(context, new acceleratedecelerateinterpolator()); } @override public void startscroll(int startx, int starty, int dx, int dy, int duration) { super.startscroll(startx, starty, dx, dy, manimationduration); } @override public void startscroll(int startx, int starty, int dx, int dy) { super.startscroll(startx, starty, dx, dy, manimationduration); } } // resize interpolator to create smooth effect on pointer according to inspiration design // this is like improved accelerated and decelerated interpolator private class resizeinterpolator implements interpolator { // spring factor private final float mfactor = 1.0f; // check whether side we move private boolean mresizein; @override public float getinterpolation(final float input) { if (mresizein) return (float) (1.0f - math.pow((1.0f - input), 2.0f * mfactor)); else return (float) (math.pow(input, 2.0f * mfactor)); } public float getresizeinterpolation(final float input, final boolean resizein) { mresizein = resizein; return getinterpolation(input); } } // model title mode public enum titlemode { all, active } // model badge position public enum badgeposition { left(left_fraction), center(center_fraction), right(right_fraction); private float mpositionfraction; badgeposition() { mpositionfraction = right_fraction; } badgeposition(final float positionfraction) { mpositionfraction = positionfraction; } } // model badge gravity public enum badgegravity { top, bottom } // out listener for selected index public interface ontabbarselectedindexlistener { void onstarttabselected(final model model, final int index); void onendtabselected(final model model, final int index); } }
布局:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.viewpager android:id="@+id/vp_horizontal_ntb" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/wrapper_ntb_horizontal"/> <framelayout android:id="@+id/wrapper_ntb_horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparentbottom="true"> <view android:id="@+id/bg_ntb_horizontal" android:layout_width="match_parent" android:layout_height="52dp" android:layout_gravity="bottom" android:background="#605271"/> <com.bzu.gxs.meunguide.navigationtabbar android:id="@+id/ntb_horizontal" android:layout_width="match_parent" android:layout_height="60dp" android:layout_gravity="center" android:background="@drawable/bg_round_circle" app:ntb_animation_duration="400" app:ntb_preview_colors="@array/red_wine" app:ntb_corners_radius="50dp" app:ntb_scaled="false" app:ntb_active_color="#8d88e4" app:ntb_inactive_color="#dddfec"/> </framelayout> </relativelayout>
activity_item.xml
<?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="match_parent" android:orientation="vertical" android:weightsum="4"> <textview android:id="@+id/txt_vp_item_page" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:background="@drawable/bg_round_rect" android:gravity="center" android:text="page" android:textcolor="#9b92b3" android:textstyle="bold"/> </linearlayout>
以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持。