首页 > 代码库 > android控件篇:ViewPager+Fragment+GridView的使用(与AndroidQuery框架结合)

android控件篇:ViewPager+Fragment+GridView的使用(与AndroidQuery框架结合)

最近看了一个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:    zhb931706659@126.com
 *2014-5-3  Nanjing,njupt,China
 */
@NoTitle
@EActivity(R.layout.image_page_grid_activity)
public class ImageLoadingPageGridActivity extends FragmentActivity{

	@ViewById
	ViewPager pager;
	
	PageAdapter adapter;
	
	@AfterViews
	void 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:    zhb931706659@126.com
 *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;
	}

	@Override
	public 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;
	}

	@Override
	public int getCount() {
		return topics.length;
	}

	@Override
	public CharSequence getPageTitle(int pos) {
		return topics[pos];
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {

		Log.d("primary", topics[position]);

		ImageGridFragment fragment = (ImageGridFragment) object;
		fragment.init();

	}

	@Override
	public 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;

	@Override
	public 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;

	}

	@Override
	public 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"?>

<RelativeLayout
	xmlns: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