Development of Android Micro-letter Bottom menu bar implementation of several methods summary _android

Source: Internet
Author: User
Tags pack

Implementation mode

There are many ways to achieve this by summarizing some of the most common ways, and then adding others later.

Viewpager + Radiogroup

Viewpager + fragmenttabhost

Viewpager +tablayout

Viewpager+radiogroup

Feel this is the simplest one, I do not put code to say that I understand the idea of it

By adding pager and radiogroup to monitor, monitor two control changes to achieve linkage

When the Viewpager display pager change will trigger the monitor, in the monitor select the corresponding RadioButton can be

When the radiogroup occurs, the monitor will also be triggered, and the corresponding pager can be set after the selected change.

Fragmenttabhost +viewpager

This way, like the one on the top, is almost always connected by listening.

If only the use of fragmenttabhost can only be achieved by clicking the tab to switch the page effect can not achieve left and right sliding and combined with viewpager just to achieve this effect

Let's take a look at Fragmenttabhost's usual methods.

-Setup () adds a label to the container Id-addtab () that sets the necessary data, such as Fragmentmanager,fragment, before using AddTab () Newtabspec () New Tab-setcurrenttab ( To set the currently displayed label-Setonchangetablisttener tab to select Change Listener-Tabhost.gettabwidget (). setdividerdrawable (NULL);  The common way to remove the spacer line-tab:-Setindicator () can set the view and string main layout <?xml version= "1.0" encoding= "Utf-8"?>
Xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns:tools= "Http://schemas.android.com/tools"
Android:id= "@+id/activity_tab_pager" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:orientation= "vertical" tools:context= "com.skymxc.demo.fragment.TabPagerActivity" > < Android.support.v4.view.ViewPager android:id= "@+id/pager" android:layout_width= "Match_parent" Android:layout_ height= "0DP" android:layout_weight= "1" ></android.support.v4.view.ViewPager> < Android.support.v4.app.FragmentTabHost android:id= "@+id/tab_host" android:layout_width= "Match_parent" Android: layout_height= "Wrap_content";</android.support.v4.app.fragmenttabhost> </LinearLayout> 

Framgent don't write layout files for simplicity. The other fragment are similar to this one.

public class Discoverfragment extends Fragment {
@Nullable
@Override public
View Oncreateview ( Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {TextView TextView
= NE W TextView (Getactivity ());
Textview.settext ("discovery");
Textview.setgravity (gravity.center);
Return TextView
}
}

The tab layout picture is simpler in the following section

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:orientation=" vertical "android:layout_width=" match_parent "
android:layout_height=" Match_parent ">
<imageview
android:id=" @+id/icon "
android:layout_width=" 30DP "
android: layout_height= "30DP"
android:layout_gravity= "center"/>
<textview
android:id= "@+id/title"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:textcolor= "@ Color/selector_font "
android:text=" discovery "
android:layout_gravity=" center "/>
</linearlayout >

Selector basically like here to stick a

<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android ">
<item android:state_selected=" true "android:drawable=" @mipmap/cb_icon_discover_selected " >
<item android:drawable= "@mipmap/cb_icon_discover_normal"/>
</selector>

Java code

Initialize Tabhost

private void Inittabhost () {
tabhost.setup (This,getsupportfragmentmanager (), r.id.pager);
Tabhost.gettabwidget (). setdividerdrawable (null);
Tabhost.addtab (Tabhost.newtabspec ("discover"). Setindicator (CreateView (R.DRAWABLE.SELECTOR_BG, "discovery"), Discoverfragment.class,null);
Tabhost.addtab (Tabhost.newtabspec ("Attach"). Setindicator (CreateView (R.drawable.selector_bg_attach, "attention") Attachfragment.class,null);
Tabhost.addtab (Tabhost.newtabspec ("message"). Setindicator (CreateView (r.drawable.selector_bg_message, "messages")), Msgfragment.class,null);
Tabhost.addtab (Tabhost.newtabspec ("info"). Setindicator (CreateView (R.drawable.selector_bg_info, "my") contactfragment.class,null);
}

Initializing pager and binding adapters

/**
* Initialize Pager binding adapter/
private void Initpager () {
fragments = new arraylist<> ();
Fragments.add (New Discoverfragment ());
Fragments.add (New Attachfragment ());
Fragments.add (New Msgfragment ());
Fragments.add (New Contactfragment ());
Fragmentadapter adapter = new Fragmentadapter (Getsupportfragmentmanager (), fragments);
Pager.setadapter (adapter);
}

Add Monitor to Tabhost and pager respectively to realize linkage

/** * for Tabhost and Viewpager to add a listener for its linkage * * private void Bindtabandpager () {Tabhost.setontabchangedlistener (new TABHOST.ONTABC Hangelistener () {/** * tab changes * @param tabid the current tab tag/@Override public void ontabchanged (String tabid) {log ("Vontabc
Hanged: "+tabid);
int position = Tabhost.getcurrenttab ();
Pager.setcurrentitem (position,true);
}
}); Pager.addonpagechangelistener (New Viewpager.onpagechangelistener () {/** * page sliding trigger * @param position the index of the first page currently appears. When the slide appears, the screen will display two pager, slide to the right position for current-1 (pager on the left), slide to the left position the current (right), * @param positionoffset 0-1 Position offset from the original position of the offset * @param positionoffsetpixels from the position offset pixel value from the original location of the cheap pixel */@Override public void onpagescrolled (i NT position, float positionoffset, int positionoffsetpixels) {log ("onpagescrolled=============position: +position+" =
===positionoffset: "+positionoffset+" ====positionoffsetpixels: "+positionoffsetpixels);} /** * Page selected * @param position the current page index/@Override public void onpageselected (int position) {Tabhost.sEtcurrenttab (position);
Log ("onpageselected==========:p osition:" +position);} /** * Trigger * @param state current sliding state is three state value * * @Override public void onpagescrollstatechanged (int state) {String states
Str= "";
Switch (state) {case viewpager.scroll_state_dragging:statestr= "dragging"; break; case viewpager.scroll_state_settling:
Statestr= "is going to the final position is about to reach the final position";
Break
Case viewpager.scroll_state_idle:statestr= "sliding stop, Current page full screen";
Break } log ("Onpagescrollstatechanged========statecode:" +state+ "====state:" +statestr);});

Full code

public class Tabpageractivity extends Appcompatactivity {private static final String TAG = "tabpageractivity"; private Fr
Agmenttabhost Tabhost;
Private Viewpager Pager;
Private list<fragment> fragments; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_tab_pager);
Tabhost = (fragmenttabhost) Findviewbyid (r.id.tab_host);
Pager = (Viewpager) Findviewbyid (R.id.pager);
Initialization of Tabhost inittabhost ();
Initialization of Pager initpager ();
Add listener associated Tabhost and Viewpager Bindtabandpager (); /** * for Tabhost and Viewpager to add a listener for its linkage * * private void Bindtabandpager () {Tabhost.setontabchangedlistener (new Tabhost.ontab ChangeListener () {/** * tab changes * @param tabid the current tab tag/@Override public void ontabchanged (String tabid) {log ("Vontab
Changed: "+tabid);
int position = Tabhost.getcurrenttab ();
Pager.setcurrentitem (position,true);
}
}); Pager.addonpagechangelistener (New Viewpager.onpagechangelistener () {/** * page sliding trigger * @param positionThe index of the first page currently appears, when the slide appears, the screen will display two pager, the right sliding position for the current-1 (the pager on the left is displayed), slide to the left position for the present (right), * @param Positionoffset 0-1 position offset from the original position of the offset * @param positionoffsetpixels from the position offset pixel value from the original location of the cheap pixel/@Override public V OID onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {log ("onpagescrolled=============
Position: "+position+" ====positionoffset: "+positionoffset+" ====positionoffsetpixels: "+positionoffsetpixels";} /** * Page selected * @param position the current page index/@Override public void onpageselected (int position) {Tabhost.setcurrenttab (pos
ition);
Log ("onpageselected==========:p osition:" +position);} /** * Trigger * @param state current sliding state is three state value * * @Override public void onpagescrollstatechanged (int state) {String states
Str= "";
Switch (state) {case viewpager.scroll_state_dragging:statestr= "dragging"; break; case viewpager.scroll_state_settling:
Statestr= "is going to the final position is about to reach the final position";
Break
Case viewpager.scroll_state_idle:statestr= "sliding stop, Current page full screen";
Break } log ("OnpagescroLlstatechanged========statecode: "+state+" ====state: "+statestr);}";} /** * Initialize Pager binding adapter/private void Initpager () {fragments = new arraylist<> (); Fragments.add (New Discoverfragmen
T ());
Fragments.add (New Attachfragment ());
Fragments.add (New Msgfragment ());
Fragments.add (New Contactfragment ());
Fragmentadapter adapter = new Fragmentadapter (Getsupportfragmentmanager (), fragments);
Pager.setadapter (adapter); /** * Initialize tabhost/private void Inittabhost () {Tabhost.setup (This,getsupportfragmentmanager (), r.id.pager); tabhost.g
Ettabwidget (). setdividerdrawable (NULL); Tabhost.addtab (Tabhost.newtabspec ("discover"). Setindicator (CreateView (R.DRAWABLE.SELECTOR_BG, "discovery"),
Discoverfragment.class,null); Tabhost.addtab (Tabhost.newtabspec ("Attach"). Setindicator (CreateView (R.drawable.selector_bg_attach, "attention")
Attachfragment.class,null); Tabhost.addtab (Tabhost.newtabspec ("message"). Setindicator (CreateView (r.drawable.selector_bg_message, "messages")),
Msgfragment.class,null); Tabhost.addtab (tabHost.newtabspec ("Info"). Setindicator (CreateView (R.drawable.selector_bg_info, "my"), Contactfragment.class,null)
; /** * Back to View * @param icon * @param tab * @return/Private View createview (int icon,string tab) {View view = GetLayout
Inflater (). Inflate (R.layout.fragment_tab_discover,null);
ImageView ImageView = (imageview) View.findviewbyid (R.id.icon);
TextView title = (TextView) View.findviewbyid (r.id.title);
Imageview.setimageresource (icon);
Title.settext (tab);
return view; } private void log (String log) {LOG.E (TAG, "=" +log+ "=");}

The effect is as follows:

Viewpager +tablayout

Tablayout You must import the expansion pack before you can use the expansion pack for input design

Tablayout can automatically associate Viewpager just specify the associated Viewpager for Tablayout.

This is convenient a lot, but also have shortcomings, after automatic association tablayout will automatically read the title of Viewpager, want to use a custom view as the tab is not possible

Import design expansion pack side-by V7

Layout here two tablayout are used to implement automatic association and manual correlation respectively

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
Android "xmlns:tools=" Http://schemas.android.com/tools "xmlns:app=" Http://schemas.android.com/apk/res-auto "
Android:id= "@+id/activity_tab_layout" android:layout_width= "match_parent" android:layout_height= "Match_parent" android:orientation= "vertical" tools:context= "com.skymxc.demo.fragment.TabLayoutActivity" > <!--Using Automatic association--
> <android.support.design.widget.tablayout android:id= "@+id/tab_layout" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" app:tabmode= "fixed" app:tabselectedtextcolor= "#f0f" app:tabindicatorcolor= "# f0f "></android.support.design.widget.TabLayout> <android.support.v4.view.viewpager android:id=" @+id/ Container "android:layout_width=" match_parent "android:layout_height=" 0DP "android:layout_weight=" 1 "></ Android.support.v4.view.viewpager> <!--to correlate--> <android.support.design.widget.tablayout Android via eavesdropping: id= "@+id/tab_layout_menu" android:layout_width= "match_parent" android:layout_height= "Wrap_content" app:tabMode= " Fixed "app:tabselectedtextcolor=" #ff0 "app:tabindicatorcolor=" #ff0 "></ Android.support.design.widget.tablayout> </LinearLayout>

Initialize the Automatically associated tab and Viewpager binding

private void Inittablayoutandpager () {
//association Viewpager Use Association tab will automatically get pager title, use AddTab will be invalid
Tablayout.setupwithviewpager (pager);
Fragments = new arraylist<> ();
Fragments.add (New Discoverfragment ());
Fragments.add (New Attachfragment ());
Fragments.add (New Msgfragment ());
Fragments.add (New Contactfragment ());
adapter = new Fragmentadapter (Getsupportfragmentmanager (), fragments);
Pager.setadapter (adapter);
}

The tab layout is the same as the above.

Adding View Auto Association for Tablayout is no use

Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (R.DRAWABLE.SELECTOR_BG, "discovery"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (R.drawable.selector_bg_attach, "attention"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (r.drawable.selector_bg_message, "message"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (R.drawable.selector_bg_info, "my"));
Tablayoutmenu.setselectedtabindicatorheight (0);//Removal indicator

Setting up Viewpager monitoring and tablayout monitoring to realize linkage

Tablayoutmenu.addontabselectedlistener (New Tablayout.ontabselectedlistener () {
/**
* Select tab to trigger
* @param tab-selected tab
/@Override public
void ontabselected (Tablayout.tab Tab) {
//associated
with pager Pager.setcurrentitem (Tab.getposition (), true);
}
/**
*
@param tab exits the selected tab
/@Override public
void ontabunselected when the selected state is exited ( Tablayout.tab tab) {
}
/**
* Trigger
* @param tab selected tab/
@Override public
void when repeating selection ontabreselected (Tablayout.tab Tab) {
}
});
Pager.addonpagechangelistener (New Viewpager.onpagechangelistener () {
@Override public
Void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {
}
@Override public
Void onpageselected (int position) {
//association tablayout
Tablayoutmenu.gettabat (position). Select ()
;
@Override public
void onpagescrollstatechanged (int state) {
}
});

Complete code

Package com.skymxc.demo.fragment;
Import Android.support.design.widget.TabLayout;
Import android.support.v4.app.Fragment;
Import Android.support.v4.view.ViewPager;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.ImageView;
Import Android.widget.TextView;
Import Com.skymxc.demo.fragment.adapter.FragmentAdapter;
Import com.skymxc.demo.fragment.fragment.AttachFragment;
Import com.skymxc.demo.fragment.fragment.ContactFragment;
Import com.skymxc.demo.fragment.fragment.DiscoverFragment;
Import com.skymxc.demo.fragment.fragment.MsgFragment;
Import java.util.ArrayList;
Import java.util.List; public class Tablayoutactivity extends Appcompatactivity {private tablayout tablayout; private Viewpager pager; private T
Ablayout Tablayoutmenu;
Private Fragmentadapter adapter;
Private list<fragment> fragments; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview(R.layout.activity_tab_layout);
Tablayout = (tablayout) Findviewbyid (r.id.tab_layout);
Pager = (Viewpager) Findviewbyid (R.id.container);
Tablayoutmenu = (tablayout) Findviewbyid (R.id.tab_layout_menu);
Inittablayoutandpager ();
If you want to use your own layout, you have to listen and correlate bindpagerandtab (); private void Bindpagerandtab () {Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview CreateView (
R.DRAWABLE.SELECTOR_BG, "discovery"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (R.drawable.selector_bg_attach, "attention"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (r.drawable.selector_bg_message, "message"));
Tablayoutmenu.addtab (Tablayoutmenu.newtab (). Setcustomview (CreateView (R.drawable.selector_bg_info, "my")); Tablayoutmenu.setselectedtabindicatorheight (0);//Remove indicator Tablayoutmenu.addontabselectedlistener (new Tablayout.ontabselectedlistener () {/** * Select tab to trigger * @param tab-selected tab/@Override public void ontabselected (Tablayout.ta b tab) {//pager associated Pager.setcurrentitem (Tab.getposition (), true); /** * Trigger * @param tab exit selected tab/@Override public void ontabunselected (Tablayout.tab tab) {}/** * Repeat selection triggers * @p
Aram tab is selected TAB */@Override public void ontabreselected (Tablayout.tab tab) {}}); Pager.addonpagechangelistener (New Viewpager.onpagechangelistener () {@Override public void onpagescrolled (int Position, float positionoffset, int positionoffsetpixels) {} @Override public void onpageselected (int position) {//Associated Ta
Blayout Tablayoutmenu.gettabat (position). Select ();
@Override public void onpagescrollstatechanged (int state) {}});
The private void Inittablayoutandpager () {//Association Viewpager uses the Association tab to automatically obtain the title of the pager, which is invalid with AddTab
Tablayout.setupwithviewpager (pager);
Fragments = new arraylist<> ();
Fragments.add (New Discoverfragment ());
Fragments.add (New Attachfragment ());
Fragments.add (New Msgfragment ());
Fragments.add (New Contactfragment ());
adapter = new Fragmentadapter (Getsupportfragmentmanager (), fragments);
Pager.setadapter (adapter); } Private VIew createview (int icon, String tab) {View view = Getlayoutinflater (). Inflate (R.layout.fragment_tab_discover,null);
ImageView ImageView = (imageview) View.findviewbyid (R.id.icon);
TextView title = (TextView) View.findviewbyid (r.id.title);
Imageview.setimageresource (icon);
Title.settext (tab);
return view; }
}

Effect chart

Here, stick the Viewpager adapter.

public class Fragmentadapter extends Fragmentpageradapter {
list<fragment> fragments;
Private string[] titles = new string[]{"Discovery", "Attention", "message", "my"};
Public Fragmentadapter (Fragmentmanager fm,list<fragment> fragments) {
super (FM);
This.fragments =fragments;
}
@Override public
Fragment getitem (int position) {return
fragments.get (position);
}
@Override public
int GetCount () {return
fragments ==null? 0:fragments.size ();
}
@Override public
charsequence getpagetitle (int position) {return
titles[position];
}

At present, summed up these several ways to think of other ways to summarize

About the github:https://github.com/sky-mxc/androiddemo/tree/master/fragment of this demo

The above is a small series to introduce the Android development of micro-letter bottom menu bar to achieve a summary of several methods, I hope to help you!

Related Article

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.