Viewpager and Viewpager indicators are used in Android applications to make tab tags _android

Source: Internet
Author: User

First, the basic usage of Viewpageindicator open source framework
we have to go to GitHub to download this library, download the address: https://github.com/JakeWharton/Android-ViewPagerIndicator, download down after you can run the example, To see what effect we need and then change it to the effect we want.

1. How to use open source framework
1th Step: Improt Library project
2nd step: Import the library into our own new project
From the GitHub on the download down this zip package, there will be a library file, is libraries engineering, there is also a sample, is provided by the author (will sample this project import, you can see the author provides a variety of styles of indicator, As a reference). If you want to develop your own style on the basis of an example of an author, you need to import the library project into Eclipse (library is a repository project that we need to use as a dependent library for our own projects). Then create a new project, New Project Libs Directory has Android-support-v4.jar, this must be deleted, because viewpageindicator inside the library, our project does not allow two Android-support-v4.jar, do not delete our project is not compiled. Right Key Item-properties-android tab-add-Select Library project-OK, import complete.

2.MainActivity layout
there is only one viewpager in the layout, one viewpagerindicator. (This example uses one of the Viewpagerindicator:tabpagerindicator)
Note that it should be close to the top or bottom of the viewpager, in short, to be together.

 <linearlayout 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:orientation=" vertical "> <com.viewpagerindicator.tabpageindicator android:id=" @+id/indicator "Andro Id:layout_width= "Match_parent" android:layout_height= "wrap_content" android:background= "@drawable/base_action_ BAR_BG "> </com.viewpagerindicator.TabPageIndicator> <android.support.v4.view.viewpager android:id=" @+ Id/pager "android:layout_width=" match_parent "android:layout_height=" 0DP "android:layout_weight=" 1 "> </andro id.support.v4.view.viewpager> </LinearLayout> 

3.MainActivity Code
1th Step: Instantiate Viewpager, set Viewpager adapter
2nd step: Instantiate Tabpageindicator,tabpageindicator and Viewpager tied together
Step 3rd: Set up the Onpagerchangelistner listener on the indicator
Step 4th: Define Adapter (inherited Fragmentpageradapter)

Instantiate the Viewpager, then instantiate the Tabpageindicator, and then set the Tabpageindicator and Viewpager associations, which is to invoke Tabpageindicator Setviewpager ( Viewpager view) method, this way to achieve the click on the tab above, the following viewpager switch, sliding viewpager, the above tab follow the switch.
Viewpager Each item we use is fragment, use fragment can make the layout more flexible, suggest more use fragment.
When setting up a listener, you need to use the Onpagerchangelistener method provided by indicator

public class Mainactivity extends fragmentactivity {/** * tab title * * Private static final string[] title = new S 

 Tring[] {"Headline", "Real Estate", "Other Side", "Woman", "Finance", "digital", "emotion", "Technology"}; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 

  Setcontentview (R.layout.activity_main); 
  Instantiate the Viewpager, and then set the Viewpager adapter Viewpager pager = (Viewpager) Findviewbyid (R.id.pager); 
  Fragmentpageradapter adapter = new Tabpageindicatoradapter (Getsupportfragmentmanager ()); 

  Pager.setadapter (adapter); Instantiate the Tabpageindicator, then bind to Viewpager (core steps) tabpageindicator indicator = (tabpageindicator) Findviewbyid ( 
  R.id.indicator); 

  Indicator.setviewpager (pager); If you want to set the fragment changes that are contained in the listening viewpager (sliding switch pages), use Onpagechangelistener to specify a listener for it, so you can't set it directly on the Viewpager as before, To set on indicator, Indicator.setonpagechangelistener (new Onpagechangelistener () {@Override public void Onpagesel ected (int arg0) {Toast.maketext (getApplicationContext (), title[arg0], Toast.length_short). Show (); @Override public void onpagescrolled (int arg0, float arg1, int arg2) {} @Override public void on 

 pagescrollstatechanged (int arg0) {}}); /** * Defines Viewpager adapter/class Tabpageindicatoradapter extends Fragmentpageradapter {public Tabpageindica 
  Toradapter (Fragmentmanager FM) {super (FM); @Override public Fragment getitem (int position) {//Create a new Fragment to show the contents of the Viewpager item and pass parameters Fragment FRAGM 
   ent = new Itemfragment (); 
   Bundle args = new Bundle (); 
   Args.putstring ("Arg", title[position]); 

   Fragment.setarguments (args); 
  return fragment; 
  @Override public charsequence getpagetitle (int position) {return title[position% title.length]; 
  @Override public int GetCount () {return title.length;

 } 
 } 
}

4. Define Viewpager code for each item (each fragment)
This example defines only one fragment,r.layout.fragment that defines only one textview. In this fragment code, passing a Key-value data through bundle, the content is only a string. Actual development, for each Viewpager item, to design each of the different fragment layout, code content and so on. This example code is only a demonstration.

public class Itemfragment extends Fragment {

 @Override public
 View Oncreateview (Layoutinflater inflater, ViewGroup container,
   Bundle savedinstancestate) {

  //dynamically locate the layout file and find out TextView object View Contextview from this layout
  Inflater.inflate (R.layout.fragment_item, container, false);
  TextView Mtextview = (TextView) Contextview.findviewbyid (R.id.textview);

  Gets the parameters passed over by the activity
  Bundle Mbundle = getarguments ();
  String title = mbundle.getstring ("arg");

  Mtextview.settext (title);

  return contextview;
 }

 @Override public
 void onactivitycreated (Bundle savedinstancestate) {
  super.onactivitycreated ( savedinstancestate);
 } 


5.Indicator Style modification
step 1th: Add <style> in Values/styles:
In this case, 3 <style> are added; Styledindicators "is the <style> that we need, and its <item> uses the <style> of" customtabpageindicator "; > One of the <item> uses the "Customtabpageindicator.text" <style>. The
can actually write the <item> properties of the "Styledindicators" <style> all Dead under "styledindicators". However, this level of separation of the writing, enhance the reusability of the code for later maintenance and functional code additions and deletions operation.

 <style name= "styledindicators" parent= "@android: Style/theme.light" > <item name= "Vpitabpageindicatorstyle" > @style/customtabpageindicator</item> </style> <style name= "Customtabpageindicator" parent= " Widget.tabpageindicator "> <item name=" android:background "> @drawable/tab_indicator</item> <item Name= "Android:textappearance" > @style/customtabpageindicator.text</item> <item name= "android:textSize ">14sp</item> <item name=" android:dividerpadding ">8dp</item> <item name=" Android: Showdividers ">middle</item> <item name=" Android:paddingleft ">10dp</item> <item name=" Android:paddingright ">10dp</item> <item name=" Android:fadingedge ">horizontal</item> <item Name= "Android:fadingedgelength" >8dp</item> </style> <style name= "Customtabpageindicator.text" Parent= "Android:TextAppearance.Medium" > <item name= "android:typeface" >monospace</item> <item name= "Android:textcolor" > @drawable/selector_tabtext</item> </style>

 

Step 2nd: Create the drawable resource file used in <style>:
Add Tab_indicator.xml and Selector_tabtext.xml to the drawable directory.
In this example, the custom drawable resource is used, and the custom drawable is typically used with the custom style above, providing resources such as pictures, colors, and so on to support custom styles:

<selector xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:state_selected= " False "android:state_pressed=" false "android:drawable=" @android: Color/transparent "/> <item android:state_ Selected= "false" android:state_pressed= "true" android:drawable= "@android: Color/transparent"/> <item android: State_selected= ' true ' android:state_pressed= ' false ' android:drawable= ' @drawable/base_tabpager_indicator_selected "/> <item android:state_selected=" true "android:state_pressed=" true "android:drawable=" @drawable/base_ Tabpager_indicator_selected "/> </selector> <selector xmlns:android=" http://schemas.android.com/apk/ Res/android "> <item android:state_selected=" true "android:color=" #EE2C2C "/> <item = "true" android:color= "#EE2C2C"/> <item android:state_focused= "true" android:color= "#EE2C2C"/> <item

 Android:color= "@android: Color/black"/> </selector>

Step 3rd: Switch to our custom style in manifest:
In this case, it is modified directly on the application, or you can modify an activity individually

<application
 android:allowbackup= "true"
 android:icon= "@drawable/ic_launcher"
 android:label= "@ String/app_name "
 android:theme=" @style/styledindicators ">


second, viewpageindicator and Viewpager copy netease News client tab
here we introduce the main code of the writing, first look at the layout file, above a tabpageindicator, the following a viewpager, or a very simple layout slightly

<linearlayout 
 xmlns:android= "http://schemas.android.com/apk/res/android" 
 android:orientation= " Vertical " 
 android:layout_width=" fill_parent " 
 android:layout_height=" fill_parent "> 
 
 < Com.viewpagerindicator.TabPageIndicator 
  android:id= "@+id/indicator" 
  android:background= "@drawable/base _ACTION_BAR_BG " 
  android:layout_height=" wrap_content " 
  android:layout_width=" fill_parent " 
  />" 
 <android.support.v4.view.viewpager 
  android:id= "@+id/pager" 
  android:layout_width= "Fill_ Parent " 
  android:layout_height=" 0DP " 
  android:layout_weight=" 1 " 
  /> 
 
</LinearLayout> 

Mainactivity's Code

Package com.example.viewpageindicator; 
Import Android.os.Bundle; 
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.support.v4.view.ViewPager.OnPageChangeListener; 
 
Import Android.widget.Toast; 
 
Import Com.viewpagerindicator.TabPageIndicator; public class Mainactivity extends fragmentactivity {/** * tab title * * Private static final string[] title = new St 
 
 Ring[] {"Headline", "Real Estate", "Other Side", "Woman", "Finance", "digital", "emotion", "Technology"}; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
   
  Setcontentview (R.layout.activity_main); 
  Viewpager's Adapter Fragmentpageradapter adapter = new Tabpageindicatoradapter (Getsupportfragmentmanager ()); 
  Viewpager pager = (Viewpager) Findviewbyid (R.id.pager); Pager.setadapter (ADAPter); Instantiate the Tabpageindicator and then set the Viewpager associated tabpageindicator indicator = (tabpageindicator) Findviewbyid (R.id.indicator) 
  ; 
   
  Indicator.setviewpager (pager);  
   If we want to set up the listener for Viewpager, we can use indicator to set the Indicator.setonpagechangelistener (new Onpagechangelistener () {@Override public void onpageselected (int arg0) {Toast.maketext (Getapplicationcontext (), title[arg0], toast.length_short). 
   Show (); @Override public void onpagescrolled (int arg0, float arg1, int arg2) {} @Override P 
   
 ublic void onpagescrollstatechanged (int arg0) {}}); 
  /** * Viewpager Adapter * @author Len * * */class Tabpageindicatoradapter extends Fragmentpageradapter { 
  Public Tabpageindicatoradapter (fragmentmanager FM) {super (FM); @Override public Fragment getitem (int position) {//Create a new Fragment to show the contents of the Viewpager item and pass parameters Fragment Frag 
   ment = new Itemfragment (); 
Bundle args = new Bundle ();   Args.putstring ("Arg", title[position]); 
    
   Fragment.setarguments (args); 
  return fragment; 
  @Override public charsequence getpagetitle (int position) {return title[position% title.length]; 
  @Override public int GetCount () {return title.length; 
 } 
 } 
 
}

We instantiate the Viewpager and then instantiate the Tabpageindicator, and to set the Tabpageindicator and Viewpager associations, we call Tabpageindicator Setviewpager ( Viewpager view) method, this way we have achieved click on the tab above, the following viewpager switch, sliding viewpager above the tab followed the switch, Viewpager each item we use is fragment, The use of fragment can make our layout more flexible, so we suggest that you use fragment, you will find that he is really good use, there is a little need to pay attention to the place, when we need to set up the Viewpager monitoring, We used to set Onpagechangelistener directly with Viewpager.setonpagechangelistener, and now we can't look like this, Tabpageindicator provides a way to set up onpagechangelistener, we need to call Tabpageindicator.setonpagechangelistener to set up listening
  Viewpager's item, that is, fragment, I only used a textview to show the tab title passed from Mainactivity, just to simulate the actual use of us, from the activity pass parameters to the fragment, I will not post the layout, the code is also relatively simple, directly look at the code.

 package com.example.viewpageindicator; 
Import Android.os.Bundle; 
Import android.support.v4.app.Fragment; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
 
 
Import Android.widget.TextView; public class Itemfragment extends Fragment {@Override public View oncreateview (Layoutinflater inflater, ViewGroup C Ontainer, Bundle savedinstancestate) {View Contextview = inflater.inflate (R.layout.fragment_item, container, F 
  Alse); 
   
  TextView Mtextview = (TextView) Contextview.findviewbyid (R.id.textview); 
  Gets the parameters passed over by the activity Bundle Mbundle = getarguments (); 
   
  String title = mbundle.getstring ("arg"); 
   
  Mtextview.settext (title); 
 return contextview; @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate 
 ); } 
 
} 

Of course, through a few steps above we can not imitate NetEase news, we must also simply modify its style, some things I was directly from the open source framework Actionbarsherlock and Viewpager imitation NetEase news client out, However, the style modification here is much simpler than using viewpageindicator, and the style is as follows

<style name= "styledindicators" parent= "@android: Style/theme.light" > <item name= "Vpitabpageindicatorstyle" > @style/customtabpageindicator</item> </style> <style name= "Customtabpageindicator" parent= " Widget.tabpageindicator "> <item name=" android:background "> @drawable/tab_indicator</item> <item Name= "Android:textappearance" > @style/customtabpageindicator.text</item> <item name= "android:textSize ">14sp</item> <item name=" android:dividerpadding ">8dp</item> <item name=" Android: Showdividers ">middle</item> <item name=" Android:paddingleft ">10dp</item> <item name=" Android:paddingright ">10dp</item> <item name=" Android:fadingedge ">horizontal</item> <item Name= "Android:fadingedgelength" >8dp</item> </style> <style name= "Customtabpageindicator.text" Parent= "Android:TextAppearance.Medium" > <item name= "android:typeface" >monospace</item> <item name= "Android:textcolor" > @drawable/selector_tabtext</item> </style> 
 

Through the above simple several steps we have realized to the NetEase news imitation, next we run the project to look down the effect

Third, summary
it's easy to implement this tab tag with Viewpageindicator, and there are a variety of indicators in the viewpageindicator, relative to the Actionbarsherlock, Viewpageindicator more flexible, and modify the Actionbarsherlock style is more complex, if your project useful to actionbarsherlock this library, you can use to implement tab paging, if the tab also add navigation bar, Actionbarsherlock can only use Actionbar to achieve slightly, and the use of viewpageindicator we can more flexible use of their own layout, we still recommend the use of Viewpageindicator, this is my personal view.

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.