Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android控件篇:ViewPager+Fragment+GridView的使用(與AndroidQuery框架結合)

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

編輯:關於Android編程

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

\

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

最外層Activity的布局文件




    

    

        
    


相應的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{

	@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:    [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;
	}

	@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 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 entries) {

		AQUtility.debug("render setup");
		ArrayAdapter aa = new ArrayAdapter(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 convertAll(XmlDom xml) {
		List entries = xml.children("entry");
		List result = new ArrayList();
		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 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;
	}
}

布局文件




	
    
    
    
	


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

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

android開發聯盟QQ群:272209595

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved