GridView 左右翻页的实现

原创 2016年05月30日 15:46:46
package com.boyue.dreamsetting;

import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.boyue.adapter.DreamAdapter;
import com.boyue.bean.Picture;
import com.boyue.dreamsetting.ScreenService.FileBinder;
import com.boyue.imagehandler.Comic;
import com.boyue.util.XmlUitl;

/**
 * 
 * @description: TODO
 * @author: guo
 * @time: Dec 10, 2015 11:34:37 AM
 */
public class MainActivity extends Activity implements OnTouchListener,
		OnGestureListener {

	private final static String UPDATE_SCREEN_ACTION = "com.boyue.dreamsetting.service";
	private final static String DREAM_PATH = Environment
			.getExternalStorageDirectory().getPath() + "/ScreenSaver";
	private final static String SELECTED_IMAGE_FILE_NAME = DREAM_PATH
			+ "/image.xml";
	private ScreenService mScreenService;
	private GridView mGridView;
	private LinearLayout title_ll;
	private DreamAdapter mDreamAdapter;
	private ArrayList<Picture> mDreamData; // 已经选择作为壁纸的图片集合
	private ArrayList<Picture> mPictureData; // 某个目录下所有的图片数据集合
	private ArrayList<Picture> mPageData; // 某页显示的数据集合
	private GestureDetector gestureDetector_;
	private Comic mComic;
	private int totalPage_; // 总共页数
	private int currentPage_ = 1; // 当前页数
	private int itemPerPage_ = 9; // 每页Item数

	private int countPage = 0; // 计量当前已经翻几页了
	private int settingCnt = 0; // 系统设置几页刷新
	private int index = 0; // 某条数据在图片数据集合中的索引

	/** 定交ServiceConnection,用于绑定Service的 */
	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName className, IBinder service) {
			// 已经绑定了LocalService,强转IBinder对象,调用方法得到LocalService对象
			FileBinder binder = (FileBinder) service;
			mScreenService = binder.getService();
			init();
		}

		public void onServiceDisconnected(ComponentName arg0) {
			mScreenService = null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		gestureDetector_ = new GestureDetector(this);
		mGridView = (GridView) findViewById(R.id.myGrid);
		title_ll = (LinearLayout) findViewById(R.id.title_ll);
		title_ll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		Intent intent = new Intent();
		intent.setClass(this, ScreenService.class);
		bindService(intent, mConnection, BIND_AUTO_CREATE);
	}

	private void init() {
		mComic = mScreenService.getComic();
		mPictureData = mScreenService.getPictureDatas(mComic);
		updatePictureState(); // 获取已经选中的图片,并设置其状态
		fillViewData();
		gridViewListenerInit();

	}

	private void updatePictureState() {
		// 获得待机图片的集合
		mDreamData = XmlUitl.domResolveXML(SELECTED_IMAGE_FILE_NAME);
		for (Picture picture : mDreamData) {
			mPictureData.get(picture.getPosition()).setChecked(true);
		}
	}

	public void gridViewListenerInit() {
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
				checkBox.toggle();
				Picture picture = mPictureData.get((currentPage_ - 1)
						* itemPerPage_ + position);
				if (checkBox.isChecked()) {
					picture.setChecked(true);
					mDreamData.add(picture);
				} else {
					picture.setChecked(false);
					for (int i = 0; i < mDreamData.size(); i++) {
						if (mDreamData.get(i).getPosition() == picture
								.getPosition()) {
							mDreamData.remove(i);
						}
					}
				}
			    mDreamAdapter.notifyDataSetChanged();
			}
			});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		try {
			settingCnt = Settings.System.getInt(getContentResolver(),
					"fullscreen_flush");
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onResume();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		updateView();
		super.onRestart();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i("gcy", "mDreamData.size = " + mDreamData.size());
		createImageXML(mDreamData);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Log.i("gcy", "MainActivity onDestroy()---");
		super.onDestroy();
		if (mConnection != null) {
			unbindService(mConnection);
		}
	}

	public String createImageXML(List<Picture> datas) {
		StringWriter xmlWriter = new StringWriter();
		try {
			SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory
					.newInstance();
			TransformerHandler handler = factory.newTransformerHandler();

			Transformer transformer = handler.getTransformer(); // 设置xml属性
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			transformer.setOutputProperty(OutputKeys.VERSION, "1.0");

			StreamResult result = new StreamResult(xmlWriter); // 保存创建的xml
			handler.setResult(result);

			handler.startDocument();
			AttributesImpl attr = new AttributesImpl();

			attr.clear();
			attr.addAttribute("", "", "author", "", "gcy");
			attr.addAttribute("", "", "date", "", "2015-12-15");
			handler.startElement("", "", "root", attr);

			int size = datas.size();
			for (int i = 0; i < size; i++) {
				attr.clear();
				handler.startElement("", "", "image", attr);

				attr.clear();
				handler.startElement("", "", "path", attr);
				String path = datas.get(i).getPath() + "";
				handler.characters(path.toCharArray(), 0, path.length());
				handler.endElement("", "", "path");

				attr.clear();
				handler.startElement("", "", "name", attr);
				String name = datas.get(i).getName();
				handler.characters(name.toCharArray(), 0, name.length());
				handler.endElement("", "", "name");

				attr.clear();
				handler.startElement("", "", "position", attr);
				int positon = datas.get(i).getPosition();
				handler.characters((String.valueOf(positon)).toCharArray(), 0,
						(String.valueOf(positon)).length());
				handler.endElement("", "", "position");

				handler.endElement("", "", "image");
			}

			handler.endElement("", "", "root");
			handler.endDocument();

		} catch (TransformerFactoryConfigurationError e) { // SAXTransformerFactory.newInstance
			e.printStackTrace();
		} catch (TransformerConfigurationException e) { // factory.newTransformerHandler
			e.printStackTrace();
		} catch (IllegalArgumentException e) { // transformer.setOutputProperty
			e.printStackTrace();
		} catch (SAXException e) { // handler.startDocument
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		savedXML(SELECTED_IMAGE_FILE_NAME, xmlWriter.toString());
		return xmlWriter.toString();
	}

	// 写数据
	public void savedXML(String fileName, String writestr) {
		try {
			FileOutputStream fout = new FileOutputStream(fileName);
			byte[] bytes = writestr.getBytes();
			fout.write(bytes);
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		float distance = e1.getX() - e2.getX(); // 横向位移
		if (Math.abs(distance) > Utils.FLING_MIN_DISTANCE) {
			if (distance > 0)// nextPage
			{
				if (currentPage_ == totalPage_) {
					currentPage_ = 1;
				} else {
					currentPage_++;
				}

				countPage++;
				if (countPage >= settingCnt) {
					getWindow().getDecorView().invalidate(-1010, -1010, -1010,
							-1010);
					countPage = 0;
				}
				updateView();

			} else {
				if (currentPage_ > 1) {
					currentPage_--;
				} else {
					currentPage_ = totalPage_;
				}
				countPage++;
				if (countPage >= settingCnt) {
					getWindow().getDecorView().invalidate(-1010, -1010, -1010,
							-1010);
					countPage = 0;
				}
				updateView();
			}
		}

		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return gestureDetector_.onTouchEvent(event);
	}

	public boolean dispatchTouchEvent(MotionEvent event) {
		if (gestureDetector_.onTouchEvent(event)) {
			event.setAction(MotionEvent.ACTION_CANCEL);
		}
		return super.dispatchTouchEvent(event);
	}

	private synchronized void updateView() {
		clearViewData(); // 清除当前页的数据
		fillViewData(); // 重新添加数据
	}

	private void clearViewData() {
		mGridView.removeAllViewsInLayout();
	}

	private void fillViewData() {

		if (mPageData != null) {
			// for (int j = 0; j < mPageData.size(); j++) {
			// Object value = mPageData.get(j).getThumbnailBitmap();
			// if (value != null) {
			// if (!(value instanceof Integer)) {
			// Bitmap bitmap = (Bitmap) value;
			// bitmap.recycle();
			// bitmap = null;
			// }
			// }
			// }
			mPageData.clear();
		} else {
			mPageData = new ArrayList<Picture>();
		}

		for (int i = 0; i < itemPerPage_; i++) {
			index = (currentPage_ - 1) * itemPerPage_ + i;
			if (0 == mPictureData.size()
					|| i + (currentPage_ - 1) * itemPerPage_ >= mPictureData
							.size() || null == mPictureData.get(index)) {
				break;
			}
			Picture picture = mPictureData.get(index);
			mPageData.add(picture);
		}

		mDreamAdapter = new DreamAdapter(mGridView,this, mPageData);
		mGridView.setAdapter(mDreamAdapter);
		
		gridViewListenerInit();
		setPageText();

	}

	private void setPageText() {
		totalPage_ = (itemPerPage_ + mPictureData.size() - 1) / itemPerPage_;
		if (0 == totalPage_) {
			totalPage_ = 1;
		}

		TextView pageTextView = (TextView) findViewById(R.id.PageTextView);
		String pageTextString = String.valueOf(currentPage_) + " / "
				+ String.valueOf(totalPage_);
		pageTextView.setText(pageTextString);
	}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Android基础总结(精华完整版)

1. 前言 1.1. 什么是3G、4G Ÿ 第三代移动通信技术(3rd - Generation),速率一般在几百Kbps,较之前的2G和2.5G在数据传输速度上有很大提升。 Ÿ 第四代移动通信...
  • dyonline2012
  • dyonline2012
  • 2013年08月26日 21:25
  • 3715

gridview 实现横向分页滑动效果的两种实现方案

方案一: 楼主在网上找的,能够实现横向滑动,但并没有分页的效果,楼主觉得简单实用就一并贴出来了,下面看代码: DisplayMetrics dm; private void setValue...
  • u010948188
  • u010948188
  • 2015年09月08日 17:21
  • 3527

android GridView 在TV上,上下翻页的时候平滑滑动的实现

应该做过android tv开发的同学都知道,在TV上使用GridView的时候,如果焦点上下移动的时候,如果移动到在屏幕上可见的第一行或者最后一行的时候,如果再继续上下移动, 的话,是比较生硬呆滞...
  • hua631150873
  • hua631150873
  • 2017年07月11日 16:58
  • 504

Android中如何实现多行、水平滚动的分页的Gridview?

功能要求: (1)比如每页显示2X2,总共2XN,每个item显示图片+文字(点击有链接)。 如果单行水平滚动,可以用Horizontalscrollview实现。 如果是多行水平滚动,则结合G...
  • wuzoujing
  • wuzoujing
  • 2013年06月08日 10:19
  • 24965

gridview整页翻页的滑动,上滑和下滑

提前声明:本篇博客是基于电视机顶盒的,全部操作是用遥控器。 转载请注明出处:、、、、 在看本篇文章之前,你需要了解平滑滚动的相关知识。 关于gridview的平滑滚动,你可以查看http://b...
  • HarryWeasley
  • HarryWeasley
  • 2015年07月07日 09:00
  • 3013

android之实现上下左右翻页效果

如果实现上下或者左右翻页效果,我们借助下这个开源项目:https://github.com/openaphid/android-flip Aphid FlipView是一个能够实现Flipboard翻...
  • GULINHAI12
  • GULINHAI12
  • 2014年12月28日 17:08
  • 5774

android左右滑动翻页查看图片

java部分代码 package com.xpc.onflingdemo; import java.io.File; import android.app.Activity; import an...
  • fishorbird
  • fishorbird
  • 2015年10月31日 20:16
  • 1414

使用jsp实现翻页功能

使用jsp实现翻页功能
  • u012156133
  • u012156133
  • 2013年12月06日 15:56
  • 1999

Android实战技巧之七:按钮控制ViewPager的左右翻页

为了实现左右翻页的效果,使用了ViewPager,它会很方便的实现左右滑动后翻页。 这时需要自己也加上两个button来实现同样的操作,如何实现呢?网上一篇blog帮了忙啦。 【Android】按钮控...
  • lincyang
  • lincyang
  • 2014年03月08日 20:38
  • 14877

Android中手势滑动翻页之GestureDetector总结

写作缘由:最近在做左右滑动翻页效果,代码写出来经过3天调试毫无进展,经过网上多次搜索和自己亲自实现,在这里写个总结供自己学习也为大家提供个方便,避免以后大家走弯路,由于我写的项目比较繁琐,就不自己写D...
  • Demo006
  • Demo006
  • 2016年04月28日 10:30
  • 1184
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:GridView 左右翻页的实现
举报原因:
原因补充:

(最多只允许输入30个字)