Android:viewpager extension--Viewpagerindicator with navigation (with image cache, loading images asynchronously)

Source: Internet
Author: User

Everyone has used Viewpager, GitHub on the Viewpager to expand, navigation style richer, this open source project is viewpagerindicator, very useful, but the example is relatively simple, actually used to do a lot of expansion, For example, in the fragment image cache and image asynchronous loading.


The following is the Viewpagerindicator source code after the effect of the operation, we have seen, I superfluous cut a few pictures;



Download source Please click here






=========================================== Gorgeous split-line ========================================


Here is my modified, can be loaded asynchronously picture, picture cache:



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 * * For more details please visit the blog: http://blog.csdn.net/lyc66666666666 */public class Sampletabsdefault extends Fragmentac tivity {//tab title private static final string[] CONTENT = new string[] {"Recent", "Artists", "Albums", "Songs", "Playlis TS "," 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 subfragment does not execute 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 When initializing item, the GetItem is called once, * and the second return item does not call the GetItem method, but the Subfragment method of Oncreateview; This means that the getItem is called only once when associated with Fragment, not later, */@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 * * For more details please visit the blog: http://blog.csdn.net/lyc66666666666 */@SuppressLint ("Validfragment") public class Subfragment extends Fragment {Priva Te 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 Get Done"); ImageView image = (ImageView) V.findviewbyid (r.id.img); Image.setbackground ( imagedrawable);});        return v;} /*** Define callback Interface */public interface Imagecallback {public void imageloaded (drawable imagedrawable, String imageUrl);} /** * Asynchronously loading picture */static class Asyncimageloader {global Global;public Asyncimageloader () {global = Global.getinstance ();} /** * Create a sub-line loads download Picture * Sub-line loads loading the picture to handler processing (the child thread cannot update the UI, and handler is in the main thread, can update the UI) * Handler again to the imagecallback,imagecallback need themselves to achieve , the callback parameters can be processed here * * @param imageUrl: Image URL to be loaded * @param imagecallback: * @return */public drawable loaddrawable (Final Str ing imageurl,final imagecallback imagecallback) {//If a picture is present 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);//execute callback return drawable;}} /** * Execute callback in main thread, update view */final Handler Handler = new Handler () {public void Handlemessage (Message message) {imagecallback.im Ageloaded ((drawable) message.obj, IMAGEURL);}};/** * Create a sub-thread to access the network and load the picture, handing the result to handler processing */new Thread () {@Overridepublic void run () {drawable drawable = Loadimagefromurl (i Mageurl);//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 * * More details please visit the blog: http://blog.csdn.net/lyc66666 666666 */public class Global {//Soft reference, use memory for temporary cache (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 "> & LT;USES-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission Android : Name= "Android.permission.INTERNET"/> <application android:allowbackup= "true" android:i                         con= "@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>       </activity> </application></manifest> 



Click to download the source code

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.