Android advanced tutorial (28th)-Use of the android viewpager control (based on the viewpager horizontal album )!!!

Source: Internet
Author: User

Hello everyone, I believe there must be a lot of listview controls for everyone. They are slide vertically and use convertview. We can load thousands of data, but sometimes we have this requirement, such as photo album, we want to slide horizontally, and there is a lot of data, this time viewpager controls will come in handy, viewpager use when we need to import a third-party package android-support-v4.jar package, which is provided by Google, this package contains controls such as fragment viewpager. You can use the fragment control before 3.0 ~

Next, let's talk about the usage of viewpager. viewpager and viewflipper are similar in usage, but they are easier to use and have a good sliding effect on the left and right, and there are adapter --- pageradapter base class similar to listview, in this way, memory can be recycled and reused. The following methods are commonly used in pageradapter:

Void destroyitem (view container, int position, object) When sliding left and right here, the previous itemview is recycled.

Int getcount () number of entries displayed in viewpager.

Object instantiateitem (view container, int position) initializes itemview.

To make it easy for everyone to grasp, I wrote a simple example to implement the horizontal sliding function of the album. First, I customized the itemview ---- viewpageritemview of viewpager. Here I made the definition of the initialized view, and reclaim memory for reloading. The data source is jsonobject. the second is to implement the pageradapter adapter viewpageradater. The data source here is jsonarray. then viewpager is named viewpagerdemoactivity. java activity. The specific implementation steps are as follows:

Step 1: Create an android project viewpagerdemoactivity. The directory structure is shown in:

Step 2: Create a viewpageritemview. Java here is the itemview of the album. The Code is as follows:

Package COM. tutor. viewpager; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import android. content. context; import android. graphics. bitmap; import android. util. attributeset; import android. view. layoutinflater; import android. view. view; import android. widget. framelayout; import android. widget. imageview; import android. widget. textview;/*** @ author frankiewei * itemview of the album, custom view. easy to reuse. */public class viewpageritemview extends framelayout {/*** image imageview. */private imageview malbumimageview;/*** textview of the image name. */private textview malbumnametextview;/*** bitmap of the image. */private bitmap mbitmap;/*** specifies the jsonobject class for displaying images. */private jsonobject mobject; Public viewpageritemview (context) {super (context); setupviews ();} public viewpageritemview (context, attributeset attrs) {super (context, attrs ); setupviews ();} // initialize view. private void setupviews () {layoutinflater Inflater = layoutinflater. from (getcontext (); view = Inflater. inflate (R. layout. viewpager_itemview, null); malbumimageview = (imageview) view. findviewbyid (R. id. album_imgview); malbumnametextview = (textview) view. findviewbyid (R. id. album_name); addview (View);}/*** fill in data for a total of external calls. * @ Param object */Public void setdata (jsonobject object) {This. mobject = object; try {int resid = object. getint ("resid"); string name = object. getstring ("name"); // in practice, if the image is time-consuming, it should make a thread pull the image asynchronously. Otherwise, the UI thread will be stuck. malbumimageview. setimageresource (resid); malbumnametextview. settext (name);} catch (jsonexception e) {e. printstacktrace () ;}/ *** memory is recycled here. external call. */Public void recycle () {malbumimageview. setimagebitmap (null); If (this. mbitmap = NULL) | (this. mbitmap. isrecycled () return; this. mbitmap. recycle (); this. mbitmap = NULL;}/*** reload. external call. */Public void reload () {try {int resid = mobject. getint ("resid"); // in practice, if the image is time-consuming, it should make a thread pull the image asynchronously. Otherwise, the UI thread will be stuck. malbumimageview. setimageresource (resid);} catch (jsonexception e) {e. printstacktrace ();}}}

The viewpageritemview XML file viewpager_itemview.xml code is as follows:

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <ImageView     android:id="@+id/album_imgview"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:contentDescription="@string/app_name"    android:scaleType="fitXY"    /><TextView    android:id="@+id/album_name"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_gravity="bottom|center_horizontal"     android:textColor="#B2191919"    /></FrameLayout>

Step 3: Create a viewpageradapter. Java inheritance and pageradapter. The Code is as follows:

Package COM. tutor. viewpager; import Java. util. hashmap; import Org. JSON. jsonarray; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import android. content. context; import android. OS. parcelable; import android. support. v4.view. pageradapter; import android. support. v4.view. viewpager; import android. view. view;/*** @ author frankiewei * album adapter. */public class viewpageradapter extends pageradapter {/*** context */private context mcontext;/*** data source, which is jsonarray */private jsonarray mjsonarray; /*** hashmap stores the location of the photo and itemview. */private hashmap <integer, viewpageritemview> mhashmap; Public viewpageradapter (context, jsonarray arrays) {This. mcontext = context; this. mjsonarray = arrays; mhashmap = new hashmap <integer, viewpageritemview> () ;}// here for recycling. When we slide left and right, early images will be recycled. @ overridepublic void destroyitem (view container, int position, object) {viewpageritemview itemview = (viewpageritemview) object; itemview. recycle () ;}@ overridepublic void finishupdate (view) {}// the number of album records returned here is the same as baseadapter. @ overridepublic int getcount () {return mjsonarray. length () ;}// here is the initialization of viewpageritemview. if viewpageritemview already exists, // reload it again, there is no new one and the data is filled. @ overridepublic object instantiateitem (view container, int position) {viewpageritemview itemview; If (mhashmap. containskey (position) {itemview = mhashmap. get (position); itemview. reload ();} else {itemview = new viewpageritemview (mcontext); try {jsonobject dataobj = (jsonobject) mjsonarray. get (position); itemview. setdata (dataobj);} catch (jsonexception e) {e. printstacktrace ();} mhashmap. put (Position, itemview); (viewpager) container ). addview (itemview) ;}return itemview ;}@ overridepublic Boolean isviewfromobject (view, object) {return view = Object ;}@ overridepublic void restorestate (parcelable arg0, classloader arg1) {}@ overridepublic parcelable savestate () {return NULL ;}@ overridepublic void startupdate (view ){}}

Step 4: Modify the viewpagerdemoactivity. Java code of the main activity class as follows:

Package COM. tutor. viewpager; import Org. JSON. jsonarray; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import android. app. activity; import android. OS. bundle; import android. support. v4.view. viewpager;/*** @ author frankiewei * demo used by the viewpager control. */public class viewpagerdemoactivity extends activity {/*** the total number of albums is defined as 100. */Private Static final int album_count = 100;/*** album resources. network data or local album is used in actual development. */Private Static final int album_res [] = {R. drawable. test1, R. drawable. test2, R. drawable. test3, R. drawable. test4, R. drawable. test5, R. drawable. test6}; private viewpager mviewpager;/*** adapter. */private viewpageradapter mviewpageradapter;/*** data source. */private jsonarray mjsonarray; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); setupviews ();} private void setupviews () {// initialize jsonarray to provide data sources for viewpageadapter. mjsonarray = new jsonarray (); For (INT I = 0; I <album_count; I ++) {jsonobject object = new jsonobject (); try {object. put ("resid", album_res [I % album_res.length]); object. put ("name", "album" + I); mjsonarray. put (object);} catch (jsonexception e) {e. printstacktrace () ;}} mviewpager = (viewpager) findviewbyid (R. id. viewpager); mviewpageradapter = new viewpageradapter (this, mjsonarray); mviewpager. setadapter (mviewpageradapter );}}

The main. xml layout code is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="fill_parent"        android:layout_height="fill_parent"         /></LinearLayout>

Step 5 run the command to view the effect:

Running effect 1 running effect 2

OK. I will write it here today. The code comments are also clear. If you have any questions, leave a message! The link below is the source code for beginners to learn and use. Let's talk about it today. Thank you !!!

Click to enter the source code ==>

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.