Android UI learning notes: navigation using ViewPager
The usage of ViewPager is shown in (graph source network). When we slide the screen left and right, we will switch from a page card to the next page card.
By default, three ViewPager objects are loaded in a group. For example, view1 view2 view3. When we move left, view1 is destroyed,
View4 (if any) is instantiated and loaded into view2 view3 view4.
To use ViewPager, follow these steps:
①Create a data source List Or List .
②Bind the data source to the adapter. different data sources have different adapters.
③Then, bind the adapter to the current ViewPager.
Different adapters are used when the filled content is different.
The data source corresponding to the PagerAdapter is List. Can dynamically load the page card and destroy the page card.
The data source corresponding to the FragmentPagerAdapter is List. The page card cannot be dynamically loaded. Destroy the page card and import it all at once.
The data source corresponding to the FragmentStatePagerAdapter is List. Can dynamically load the page card and destroy the page card.
①Create a data source List Or List .
ViewPager can be filled with View and Fragment as page cards.
Here we take the View as an example. FirstCreate a simple layoutThere is only one TextView to display the page cards.
Then, set this layout in the Activity.
Convert to View objectThere are two ways to do this.
// Method 1: LayoutInflater lf = getLayoutInflater (). from (this); // obtain the LayoutInflater object lf. inflate (resource, root); // then inflate to get the view. resource indicates the layout file of layout, and root indicates the root control to be appended to the resource file. // The second method is View. inflate (context, resource, root); // context indicates the current context, resouce and root refer to the above explanation. // The root here means to load the view converted by layout to which ViewGroup, which is not required here. so set to null
The view is displayed in
Add to List setIn this way, the first step is to create a data source.
ViewList = new ArrayList
(); For (int I = 0; I <4; I ++) {View view = View. inflate (MainActivity. this, R. layout. view, null); (TextView) view. findViewById (R. id. pageText )). setText ("this is the" + I + "View"); viewList. add (view );}
②Bind the data source to the adapter. different data sources have different adapters.
We need to write an adapter by ourselves, because we previously used View to fill, so PagerAdapter is used here.
Public class MyViewPagerAdapter extends PagerAdapter {List
ViewList; // View set List of the page card
TitleList; // The title set of the page card public MyViewPagerAdapter (List
ViewList, List
TitleList) {// custom constructor this. viewList = viewList; this. titleList = titleList;} @ Override public int getCount () {return viewList. size (); // number of returned page cards} @ Override public boolean isViewFromObject (View view, Object object) {return view = object; // whether the view is of the object type} @ Override public Object instantiateItem (ViewGroup container, int position) {container. addView (viewList. get (position); // instantiate a page card. When sliding left and right, return viewList is called. get (position) ;}@ Override public void destroyItem (ViewGroup container, int position, Object object) {container. removeView (viewList. get (position); // destroy a page card, called when sliding left and right} @ Override public CharSequence getPageTitle (int position) {return titleList. get (position); // set the title of the page card, such as FragmentA, FragmentB, FragmentC }}
There are some common methods to rewrite.
GetCount ()The number of page cards is returned, that is, the number of View cards you fill in.
Quantity, We use the size () method of the set to return an int.
IsViewFromObject ()View
TypeSometimes we need to determine whether the view is TextView or Button.
InstantiateItem ()This method is called when the page is view1 view2 view3, sliding left, And view4 appears.
LoadView4, forming view2 view3 view4.
DestroyItem ()It is called at the same time as the previous method,
DestroyView1 is essentially to delete view1 from ViewGroup and add view4.
GetPageTitle ()IS DISPLAYED
Title, Such as fragmengA, fragmengB, and fragmengC in the top figure.
After we write an adapter, the data source is loaded.
The second step is to write the adapter.
MyViewPagerAdapter = new MyViewPagerAdapter (viewList, titleList); // set List
Input. The constructor must be written to the adapter.
③ Bind the adapter to the current ViewPager.
Add ViewPager to the XML layout file of the Activity.
In implementation, the title of FragmentA, FragmentB, and FragmentC actually has two methods,
UsePagerTabStripOrPagerTitleStripTwo methods. Note that only one method can be used.
Then layout_gravity is used to arrange the tab. We put the tab on the top and the title on the bottom.
<android.support.v4.view.viewpager android:id="@+id/viewPager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"> <android.support.v4.view.pagertabstrip android:id="@+id/tab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" android:background="@color/yellow"> </android.support.v4.view.pagertabstrip> <android.support.v4.view.pagertitlestrip android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" android:background="@color/blue"> </android.support.v4.view.pagertitlestrip></android.support.v4.view.viewpager>
It will invalidate the tab (PagerTabStrip is a subclass of PagerTitleStrip. If you are interested, you can check the API)
Then bind the adapter.
viewPager = (ViewPager) findViewById(R.id.viewPager);viewPager.setAdapter(myViewPagerAdapter);
Additional:
④If you think the style is ugly, you can customize the style.
We recommend that you write the code to increase your impression.
// The pagerTabStrip method is as follows in pagerTabStrip. setBackgroundColor (int color); // the background color of the navigation bar pagerTabStrip. setTextColor (int color); // The text color of the navigation bar pagerTabStrip. setDrawFullUnderline (boolean drawFull); // determines whether the bottom line of the navigation bar displays pagerTabStrip. setTabIndicatorColor (int color); // the color of the selected line on the current page card
⑤ What if we use Fragment instead of a View?
By checking the API, we can know that the FragmentPagerAdapter and FragmentStatePagerAdapter areSibling relationship, AllDirect inheritanceSelf-PagerAdapter.
The difference between the two is that the FragmentPagerAdapter cannot dynamically load the page card. It imports all page cards at a time, while the FragmentStatePagerAdapter dynamically loads the page card like the PagerAdapter.
Like View, we add a data source List for the FragmentPagerAdapter adapter. And then override the methods in FragmentPagerAdapter (inherited from PagerAdapter ).
Note that the FragmentPagerAdapter loads all page cards at a time, so you do not need to override instantiateItem () and destroyItem () (these two methods are to be rewritten in the FragmentStatePagerAdapter ).
We need to import android. support. v4.app. Fragment instead of android. app. Fragment.
In addition, our Activity must inherit from FragmentActivity,
In addition, you need to use getsuppfrfragmentmanager () in the Activity to obtain the FragmentManager object in the new object.
public MyFragmentPagerAdapter(FragmentManager fm,List
fragmentList, List
titleList) { super(fm); this.fragmentList = fragmentList; this.titleList = titleList; }
⑥Finally, we add another listener.
Public class MainActivity extends FragmentActivity implements ViewPager. onPageChangeListener {@ Override public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {System. out. println ("current is" + position + "Page card" + ", percentage of current page offset:" + positionOffset + ", the pixel position of the current page offset: "+ positionOffsetPixels); // call this method when the page card is rolling.} @ Override public void onPageSelected (int position) {Toast. makeText (MainActivity. this, "current is the" + position + "Page card", Toast. LENGTH_SHORT ). show (); // call this method when the page card changes} @ Override public void onPageScrollStateChanged (int state) {switch (state) {case 0: Toast. makeText (MainActivity. this, "sliding finished", Toast. LENGTH_SHORT ). show (); break; case 1: Toast. makeText (MainActivity. this, "press your finger", Toast. LENGTH_SHORT ). show (); break; case 2: Toast. makeText (MainActivity. this, "finger up", Toast. LENGTH_SHORT ). show (); break;} // call this method when the slide status changes}
The Demo source code of ViewPager filled with View is attached below.
Public class MainActivity extends Activity implements ViewPager. OnPageChangeListener {List
ViewList; // fill in the View data source List
TitleList; // The title set of the View. MyViewPagerAdapter myViewPagerAdapter; // The Custom View-based adapter PagerTabStrip pagerTabStrip; // The ViewPager viewPager in the navigation bar; // The filled component @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); viewList = new ArrayList
(); TitleList = new ArrayList
(); View [] views = new View [4]; for (int I = 0; I <4; I ++) {views [I] = View. inflate (MainActivity. this, R. layout. view, null); // set view. xml Conversion to View object (TextView) views [I]. findViewById (R. id. pageText )). setText ("this is the" + I + "View"); titleList. add ("page" + I + "); // add the title to the set viewList. add (views [I]); // add view to set} pagerTabStrip = (PagerTabStrip) findViewById (R. id. tab); // customize the menu bar style pagerTabStrip. setBackgroundColor (Color. YELLOW); // the background color of the navigation bar pagerTabStrip. setTextColor (Color. BLUE); // The text color pagerTabStrip in the navigation bar. setDrawFullUnderline (false); // whether the bottom line of the navigation bar displays pagerTabStrip. setTabIndicatorColor (Color. RED); // The Bottom Line color of the current page card selected in the navigation bar. myViewPagerAdapter = new MyViewPagerAdapter (viewList, titleList); viewPager = (ViewPager) findViewById (R. id. viewPager); viewPager. setAdapter (myViewPagerAdapter); // Add the adapter to ViewPager viewPager. setOnPageChangeListener (this); // sets the listener} @ Override public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {System. out. println ("current is" + position + "Page card" + ", percentage of current page offset:" + positionOffset + ", the pixel position of the current page offset: "+ positionOffsetPixels); // call this method when the page card is rolling.} @ Override public void onPageSelected (int position) {Toast. makeText (MainActivity. this, "current is the" + position + "Page card", Toast. LENGTH_SHORT ). show (); // call this method when the page card changes} @ Override public void onPageScrollStateChanged (int state) {switch (state) {case 0: Toast. makeText (MainActivity. this, "sliding finished", Toast. LENGTH_SHORT ). show (); break; case 1: Toast. makeText (MainActivity. this, "press your finger", Toast. LENGTH_SHORT ). show (); break; case 2: Toast. makeText (MainActivity. this, "finger up", Toast. LENGTH_SHORT ). show (); break;} // call this method when the sliding status changes }}
Public class MyViewPagerAdapter extends PagerAdapter {List
ViewList; List
TitleList; public MyViewPagerAdapter (List
ViewList, List
TitleList) {this. viewList = viewList; this. titleList = titleList;} @ Override public int getCount () {return viewList. size (); // number of returned page cards} @ Override public boolean isViewFromObject (View view, Object object) {return view = object; // whether the view is of the object type} @ Override public Object instantiateItem (ViewGroup container, int position) {container. addView (viewList. get (position); // instantiate a page card return viewList. get (position) ;}@ Override public void destroyItem (ViewGroup container, int position, Object object) {container. removeView (viewList. get (position); // destroy a page card} @ Override public CharSequence getPageTitle (int position) {return titleList. get (position); // set the title of the page card }}