Specific explanations for Android:viewpager extensions-navigation viewpagerindicator (with image caching, loading images asynchronously)

Source: Internet
Author: User

We've used Viewpager to do that. GitHub has a viewpager extension and a richer navigation style. This open source project Viewpagerindicator. Very useful, but the sample is relatively simple, the actual use is very not extended. For example, image caches and images are loaded asynchronously in fragment.


The following is the effect of Viewpagerindicator source code after execution. Everyone has seen it, I superfluous cut a few pictures.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">


Download source code please click here






=========================================== Gorgeous cutting line ========================================


The following is my modified, can be loaded asynchronously picture, can be picture cache:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhljnjy2njy2njy2njy=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">


Do you have a heart to see a beautiful woman?



Package Com.example.viewpagerindicatortest;import Java.util.arraylist;import Java.util.list;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 com.viewpagerindicator.tabpageindicator;/** * Fragment-based tab-style ViewPager * * * @author Andy * * Many other details please visit the blog: http://blog.csdn.net/lyc66666666666 */public class Sampletabsdefault extends Fragment Activity {//tab title private static final string[] CONTENT = new string[] {"Recent", "Artists", "Albums", "Songs", "Playl Ists "," genres "," test "};p rivate list<subfragment> List = new arraylist<subfragment> (); string[] urls = new string[] {"http://a.hiphotos.baidu.com/image/pic/item/ 3bf33a87e950352ad6465dad5143fbf2b2118b6b.jpg "," http://a.hiphotos.baidu.com/image/pic/item/ C8177f3e6709c93d002077529d3df8dcd0005440.jpg "," http://f.hiphotos.baidu.coM/image/pic/item/7aec54e736d12f2ecc3d90f84dc2d56285356869.jpg "," http://e.hiphotos.baidu.com/image/pic/item/ 9c16fdfaaf51f3de308a87fc96eef01f3a297969.jpg "," http://d.hiphotos.baidu.com/image/pic/item/ F31fbe096b63f624b88f7e8e8544ebf81b4ca369.jpg "," http://h.hiphotos.baidu.com/image/pic/item/ 11385343fbf2b2117c2dc3c3c88065380cd78e38.jpg "," http://c.hiphotos.baidu.com/image/pic/item/    3801213fb80e7bec5ed8456c2d2eb9389b506b38.jpg "};        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.simple_tabs); /* Initialize: Assemble multiple fragment * The first time you create a subfragment does not run the Oncreateview method */for (int i = 0; i < 7; i++                                        ) {subfragment fragment =new subfragment (Urls[i]); List.add (fragment);}        Viewpager pager = (Viewpager) Findviewbyid (R.id.pager); Pager.setadapter (New Myadapter (Getsupportfragmentmanager (), list));//Set Adapter TabpageindicAtor indicator = (tabpageindicator) Findviewbyid (r.id.indicator);    Indicator.setviewpager (pager);//}/** * Fragmentpageradapter used to fit fragment */    Class Myadapter extends Fragmentpageradapter {list<subfragment> mlist; Public Myadapter (Fragmentmanager fm,list<subfragment> list) {super (FM); mlist = list;} /** * Fragmentpageradapter GetItem is called once when the item is initialized. * The second return item does not call the GetItem method, but instead runs the Subfragment Oncreateview method. * This means that only one getItem is invoked when associated with the Fragment, but not in the future; */@Overridepublic Fragment getItem (int position) {return Mlist.get ( position);} /* Returns title */@Override public charsequence getpagetitle (int position) {return content[positio        n% content.length].touppercase ();        }/* * Returns the total number of pages */@Override public int GetCount () {return mlist.size (); }                    }            }



Package Com.example.viewpagerindicatortest;import Java.io.ioexception;import Java.lang.ref.softreference;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.params.coreconnectionpnames;import Android.annotation.suppresslint;import Android.graphics.drawable.drawable;import Android.os.bundle;import Android.os.handler;import android.os.Message; Import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import android.widget.imageview;/** * Viewpager based on fragment tab style; * * @author Andy * * Many other details please visit bo Guest: http://blog.csdn.net/lyc66666666666 */@SuppressLint ("Validfragment") public class Subfragment extends Fragment {pri vate static final String key_content ="Testfragment:content"; Private String mcontent = "?

??

"; Private String URL; Public subfragment (String url) {this.url = URL; System.out.println ("URL:" +url); } @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); if (savedinstancestate! = null) && Savedinstancestate.containskey (key_content)) {mcontent = Save Dinstancestate.getstring (key_content); }} View v; /** * Each page will call Oncreateview to create a component */@Overridepublic View Oncreateview (layoutinflater inflater,final viewgroup conta Iner, Bundle savedinstancestate) {v = inflater.inflate (r.layout.test, NULL), New Asyncimageloader (). loaddrawable (URL, New Imagecallback () {@SuppressLint ("Newapi") public void imageloaded (drawable imagedrawable, String imageUrl) { System.out.println ("Picture gets Finished"); ImageView image = (ImageView) V.findviewbyid (r.id.img); Image.setbackground ( imagedrawable);}); return v;} /** * Define callback interface */public interface Imagecallback {public voidimageloaded (drawable imagedrawable, String imageUrl);} /** * Asynchronously loads the picture */static class Asyncimageloader {global Global;public Asyncimageloader () {global = Global.getinstance ();} /** * Create a child thread load picture * The child thread loads the picture to the handler processing (the child thread cannot update the UI, and handler is in the main thread, able to update the UI) * Handler again to the imagecallback,imagecallback need to implement. The callback parameters can be processed here * * @param imageUrl: Image URL to load * @param imagecallback: * @return */public drawable loaddrawable (Final stri ng imageurl,final Imagecallback imagecallback) {//Assuming a picture exists in the cache, first use the cache if (Global.getcache (IMAGEURL)!=null) { SYSTEM.OUT.PRINTLN ("Presence cache ~~~~~~~~~~~~~~~~~"); softreference<drawable> softreference = Global.getcache (IMAGEURL);D rawable drawable = Softreference.get (); if ( drawable = null) {imagecallback.imageloaded (drawable, IMAGEURL);//Run callback return drawable;}} /** * Run callbacks in the main thread. Update View */final Handler Handler = new Handler () {public void Handlemessage (Message message) {imagecallback.imageloaded (Draw Able) message.obj, IMAGEURL);}};/ * * Create a sub-thread to access the network and load the picture, give the result to handler processing */new thread (){@Overridepublic void Run () {drawable drawable = Loadimagefromurl (IMAGEURL);//The downloaded picture is placed in the cache Global.setcache (IMAGEURL, New Softreference<drawable> (drawable)); Message message = Handler.obtainmessage (0, drawable); handler.sendmessage (message);}}. Start (); return null;} /** * Download Picture (note the difference between HttpClient and httpurlconnection) */public drawable loadimagefromurl (String url) {try {HttpClient client = New Defaulthttpclient (); Client.getparams (). Setparameter (Coreconnectionpnames.connection_timeout, 1000*15); HttpGet get = new HttpGet (URL); HttpResponse response;response = Client.execute (Get), if (Response.getstatusline (). Getstatuscode () = = HttpStatus.SC_ OK) {httpentity entity = response.getentity ();D rawable d = Drawable.createfromstream (Entity.getcontent (), "src"); return D;} else {return null;}} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return null;}} @Overridepublic void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate); outstAte.putstring (Key_content, mcontent);}}




Package Com.example.viewpagerindicatortest;import Java.lang.ref.softreference;import Java.util.HashMap;import android.graphics.drawable.drawable;/** * Global variables. Storing picture caches as soft references * * @author Andy * * Many other details please visit the blog: http://blog.csdn.net/lyc66666666666 */public class Global {//Soft reference, using memory for temporary slow Save (program exit, or insufficient memory to clear soft reference) private static hashmap<string, softreference<drawable>> imagecache;private static Global global;public Static Global getinstance () {if (global = null) {global = new global ();} if (Imagecache = = null) {Imagecache = new hashmap<string, softreference<drawable>> ();} return global;} Store cache public void Setcache (String url, softreference<drawable> softreference) {imagecache.put (URL, SoftReference);} Gets the cache public softreference<drawable> getcache (String URL) {return imagecache.get (URL);} Clear cache public void ClearCache () {if (imagecache.size () > 0) {imagecache.clear ();}}}



Simple_tabs.xml

<?xml version= "1.0" encoding= "Utf-8"?><!--Copyright (C) Jake Wharton Licensed under the Apache License,     Version 2.0 (the "License");     You are not a use of this file except in compliance with the License. Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by Applica BLE law or agreed-in-writing, software distributed under the License is distributed on a "as is" BASIS, Withou     T warranties or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><linearlayo UT 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: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>


Test.xml

<?

XML version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android " xmlns:app=" Http://schemas.android.com/apk/res-auto " android:layout_width=" Fill_parent " android: layout_height= "Fill_parent" android:orientation= "vertical" > <imageview android:id= "@+id/img" android:layout_width= "fill_parent" android:layout_height= "Fill_parent"/></linearlayout>



Androidmainfest.xml

<?xml version= "1.0" encoding= "Utf-8"?

><manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= " Com.example.viewpagerindicatortest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk an droid:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permis Sion. INTERNET "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "Android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity Android:name= ". Sampletabsdefault "android:label=" @string/app_name "android:theme=" @style/theme.pageindicatordefault S "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </ac Tivity> </applicaTion></manifest>




Click to download source code

Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Specific explanations for Android:viewpager extensions-navigation viewpagerindicator (with image caching, loading images asynchronously)

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.