android控制項篇:ViewPager+Fragment+GridView的使用(與AndroidQuery架構結合)

來源:互聯網
上載者:User

標籤:android   des   blog   class   code   java   

最近看了一個AndroidQuery的架構,裡面的Demo,有個介面,讓博主很喜歡。左右滑動十分順暢,手感很好,於是拿來和大家分享一下。先看一下:


可以看出,上面的布局是一個Layout裡面嵌套有個ViewPager,ViewPager中包含著Fragment,Fragment的布局檔案包含了一個簡單的GridView,GridView的Item布局很簡單,就是一個100*100大小的圖片。好啦,先說這麼多,然後咱們看代碼吧。

最外層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:orientation="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>

相應的Activity的java檔案:(使用了AndroidAnnotation架構)

/* * $filename: ImageLoadingPageGridActivity.java,v $ * $Date: 2014-5-3  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is 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 protected] *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);pager.setAdapter(adapter);pager.setOffscreenPageLimit(3);//設定緩衝視圖的數目}}

大家注意:setOffscreenPageLimit的參數設定,數目越大,緩衝的越多,切換的時候,載入的越快。但,並不是越大越好,記憶體中緩衝的越多,消耗的手機資源就越多。

下面看一下PageAdapter的代碼

/* * $filename: PageAdapter.java,v $ * $Date: 2014-5-3  $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is 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,China */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]);}}

從上面的額PageAdapter的代碼可以看出,裡面總共有13個頁面。也就是左右滑動的時候,有13個Fragment。這裡,注意一下getItem方法,它返回的是一個ImageGridFragment,並且向該Fragment中傳遞了鍵為topic的索引值對。

下面看一下對應的ImageGridFragment的java檔案和布局檔案:

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=100";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(tbs.size() - 1).attr("url");}tb = tb.replaceAll("https:", "http:");Photo photo = new Photo();photo.url = url;photo.tb = tb;photo.title = title;photo.author = author;return photo;}class Photo {String tb;String url;String title;String author;}}

布局檔案

<?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>

注意:ImageGridFragment的init方法是在PageAdapter中調用的。本Demo中,init是直接使用AQuery從網路上擷取相應的資源。而對於實際的項目,我們首先檢查本機資料庫是否有相應的資源,如果有,先載入。其次,向網路中擷取,查看是否有更新,如有更新,就再在原來的基礎上,添加資料。

整個項目中得比較關鍵的布局就這麼多。整個項目:http://download.csdn.net/detail/nuptboyzhb/7287219

android開發聯盟QQ群:272209595

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.