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);
	}

}


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

相关文章推荐

使用RecyclerView实现多行水平分页的GridView效果和ViewPager效果

前些天看到有人在论坛上问这种效果怎么实现,没写过也没用过这个功能,网上查了一下,大多是使用ViewPager+GridView或者HorizontalScrollView+GridView实现,不过貌...

Android TV开发经验总结---初识TV开发

之前一直从事手机APP应用开发,由于工作的需要转入TV电视端的开发,初次接触确实有点懵逼,在TV开发过程中的处理思路跟手机还是有很大区别的,接下来将讲述下TV开发过程的经验,与大家一起分享共同学习。 ...
  • Derbe
  • Derbe
  • 2016-07-18 10:55
  • 10950

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

Android TV ViewPager翻页控制

Android TV ViewPager 翻页控制

Android TV横向滚动实现Launcher的RecyclerView第二弹

上一篇粗略的讲了一下RecyclerView,这一篇主要是就横向滚动的做一下补充 Demo下载关于RecyclerView 的焦点获取以及其他问题补充记录

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

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

gridview整页翻页的滑动,上滑和下滑,适应各种布局

提前声明:本篇博客是基于电视机顶盒的,全部操作是用遥控器。 在看这篇文章之前,你有必要去了解一下我的上一篇文章,http://blog.csdn.net/harryweasley/article/d...

Android TV开发经验总结---控件Gridview使用

前一篇我们已经讲解的基本Android TV 开发的基础技能Android TV开发经验总结---初识TV开发,接下来聊聊TV开发中所涉及到的控件运用     目前Android TV 开发的资料不是...
  • Derbe
  • Derbe
  • 2016-07-18 16:23
  • 4674

ANDROID GridView 分页平滑滑动 效果的实现(基于android TV遥控器操作)

1.android 使用GridView 实现加载大量的数据显示。未显示出来的数据可以滑动屏幕让底部的数据显示出来,但是原生态的GridView 并没有很美观平滑的一个动画来滚动数据,因此,我们可以稍...

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

提前声明:本篇博客是基于电视机顶盒的,全部操作是用遥控器。 转载请注明出处:、、、、 在看本篇文章之前,你需要了解平滑滚动的相关知识。 关于gridview的平滑滚动,你可以查看http://b...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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