Android Control article: the use of Viewpager+fragment+gridview (combined with the androidquery framework)

Source: Internet
Author: User

Recently saw a androidquery frame, the inside of the demo, there is an interface, let bloggers like it. Left and right sliding very smooth, feel good, so take to share with you. First Look at:


As can be seen, the above layout is a layout inside nested there is a viewpager,viewpager contained in the fragment,fragment of the layouts file contains a simple Gridview,gridview the item layout is very simple, is a 100*100-sized picture. OK, let's talk about it first, then let's look at the code.

Layout file for the outermost activity

<?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:o rientation= "vertical" >    <textview        android:layout_width= "fill_parent"        android:layout_height= " Wrap_content "        android:gravity=" center "        android:text=" Display 10x100 images from Picasa. "/>    < Android.support.v4.view.ViewPager        android:id= "@+id/pager"        android:layout_width= "Fill_parent        " android:layout_height= "Fill_parent" >        <android.support.v4.view.pagertabstrip            android:layout_ Width= "Wrap_content"            android:layout_height= "wrap_content"            android:layout_gravity= "top"/>    </android.support.v4.view.ViewPager></LinearLayout>

Java files for the corresponding activity: (using the androidannotation framework)

/* * $filename: IMAGELOADINGPAGEGRIDACTIVITY.JAVA,V $ * $Date: 2014-5-3 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are made by Zhenghaibo. */package Edu.njupt.zhb;import Org.androidannotations.annotations.afterviews;import Org.androidannotations.annotations.eactivity;import Org.androidannotations.annotations.notitle;import Org.androidannotations.annotations.viewbyid;import Android.support.v4.app.fragmentactivity;import android.support.v4.view.viewpager;/* * @author: Zhenghaibo *WEB:HTTP://BLOG.CSDN.NET/NUPTBOYZHB *mail: [Email prote CTED] *2014-5-3 Nanjing,njupt,china * * @NoTitle @eactivity (r.layout.image_page_grid_activity) public class Imageloadingpagegridactivity extends fragmentactivity{@ViewByIdViewPager Pager; PageAdapter adapter; @AfterViewsvoid Afterviews () {adapter = new PageAdapter (Getsupportfragmentmanager (), Imageloadingpagegridactivity.this);p Ager.setadapter (adapter);p Ager.setoffscreenpagelimit (3);//Set the number of cached views}}

Note: The Setoffscreenpagelimit parameter setting, the larger the number, the more cache, when switching, the faster the load. However, the larger the better, the more memory is cached, the more mobile resources you consume.

Let's take a look at PageAdapter's code.

/* * $filename: PAGEADAPTER.JAVA,V $ * $Date: 2014-5-3 $ * Copyright (C) Zhenghaibo, Inc. All rights reserved. * This software are made by Zhenghaibo. */package Edu.njupt.zhb;import Android.content.context;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmentstatepageradapter;import Android.util.log;import android.view.ViewGroup;/* *@ Author:zhenghaibo *WEB:HTTP://BLOG.CSDN.NET/NUPTBOYZHB *mail: [email protected] *2014-5-3 Nanjing,njupt,C Hina */public Class PageAdapter extends Fragmentstatepageradapter {private static string[] topics = {"Dog", "cat", "bird" , "Panda", "Horse", "Elephant", "Bear", "Butterfly", "monkey", "Fish", "tiger", "chicken", "Pig"}; Context Context;public PageAdapter (fragmentmanager FM, context context) {super (FM); this.context = context;} @Overridepublic Fragment getItem (int pos) {LOG.D ("primary", Topics[pos]); Bundle args = new bundle (); Args.putstring ("topic", Topics[pos]); Imagegridfragment fragment = (imagegridfragment) fragment.instantiate (context, ImageGridFragment.class.getName (), args); return fragment;} @Overridepublic int GetCount () {return topics.length;} @Overridepublic charsequence getpagetitle (int pos) {return topics[pos];} @Overridepublic void Setprimaryitem (ViewGroup container, int position, object object) {LOG.D ("primary", topics[position ]); Imagegridfragment fragment = (imagegridfragment) object;fragment.init ();} @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {log.d ("Destroyitem", topics[ Position]);}}

From the above PageAdapter code can be seen, there is a total of 13 pages. That is, when the left and right slide, there are 13 fragment. Here, notice the GetItem method, which returns a imagegridfragment, and passes a key-value pair to the fragment with the key topic.

Here's a look at the corresponding imagegridfragment Java file and layout file:

Package Edu.njupt.zhb;import Java.util.arraylist;import Java.util.list;import android.os.bundle;import Android.support.v4.app.fragment;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.arrayadapter;import Com.androidquery.AQuery ; Import Com.androidquery.callback.ajaxstatus;import Com.androidquery.util.aqutility;import Com.androidquery.util.xmldom;public class Imagegridfragment extends Fragment {private aquery aq;private aquery aq2; Private String topic;private list<photo> photos; @Overridepublic View Oncreateview (Layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {View view = Inflater.inflate (R.layout.image_grid_fragment, container, FALSE); aq = new Aquery (getactivity (), view); aq2 = new Aquery (getactivity ()); LOG.D ("Viewpagerdemo", "Oncreateview ..."); return view;} @Overridepublic void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate); TOPIC = gEtarguments (). GetString ("topic"); LOG.D ("Viewpagerdemo", "onactivitycreated ..."); Private Boolean inited;public void init () {if (aq = = NULL | | inited) return;inited = true; LOG.D ("Viewpagerdemo", "init ..."); Refresh ();} public void Refresh () {Ajaxphotos ();} private void Ajaxphotos () {String URL = "https://picasaweb.google.com/data/feed/api/all?q=" + topic + "&max-results= Aq.progress (r.id.progress). Ajax (URL, xmldom.class, 0, this, "PHOTOSCB");} public void PHOTOSCB (String URL, XmlDom xml, ajaxstatus status) {if (XML! = null) {photos = ConvertAll (XML); render (PHOTOS) ;}} private void Render (list<photo> entries) {aqutility.debug ("Render Setup"); arrayadapter<photo> AA = new arrayadapter<photo> (getactivity (), r.layout.grid_item2, entries) {public View  GetView (int position, View Convertview, ViewGroup parent) {if (Convertview = = null) {Convertview = Aq.inflate (Convertview, r.layout.grid_item2,parent);} Photo photo = GetItem (position); Aquery aq = aq2.recycle (Convertview); String TBURL = Photo.tb;if (Aq.shoulddelay (position, Convertview, parent, Tburl)) {aq.id (R.ID.TB). Clear ();} else {aq.id (R.ID.TB) . Image (Tburl, True, true, 200,r.drawable.image_missing, NULL, 0, 0);} return convertview;}; Aq.id (R.id.grid). Adapter (AA);} Private list<photo> ConvertAll (XmlDom xml) {list<xmldom> entries = Xml.children ("entry"); list<photo> result = new arraylist<photo> (); for (XmlDom entry:entries) {result.add (CONVERT (Entry));} return result;} Private Photo CONVERT (XmlDom xml) {String URL = xml.child ("content"). attr ("src"); String title = Xml.child ("title"). Text (); String author = xml.child ("author"). Text ("name"); String tb = URL; list<xmldom> TBS = xml.tags ("Media:thumbnail"), if (tbs.size () > 0) {//TB = Tbs.get (0). attr ("url"); TB = Tbs.get (t Bs.size ()-1). attr ("url");} TB = Tb.replaceall ("https:", "http:"); Photo photo = new photo ();p Hoto.url = URL;PHOTO.TB = Tb;photo.title = Title;photo.author = Author;return photo;} Class Photo {String TB; String URL; String TiTle String author;}}

Layout file

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayoutxmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " >    <gridview     android:id= "@+id/grid"    android:layout_width= "fill_parent"     android:layout_ height= "Fill_parent"    android:columnwidth= "90DP"    android:numcolumns= "Auto_fit"    android: verticalspacing= "10DP"    android:horizontalspacing= "10DP"    android:stretchmode= "ColumnWidth"    android: gravity= "center"/>        <progressbar         android:id= "@+id/progress" android:layout_width= "Wrap_    Content "     android:layout_height=" wrap_content "        android:layout_centerinparent=" true "        Android: Visibility= "Gone"        /></relativelayout>

Note: The Init method of Imagegridfragment is called in PageAdapter. In this demo, Init uses aquery directly to get the appropriate resources from the network. For the actual project, we first check whether the local database has the corresponding resources, if so, load first. Second, to get to the network to see if there are updates, if there is an update, then on the original basis, add data.

There are so many more critical layouts throughout the project. Entire project: http://download.csdn.net/detail/nuptboyzhb/7287219

Android Development Alliance QQ Group: 272209595

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.