Android ListView 实现 GridView 用以实现GridView的下拉刷新

最近项目中碰到GridView下拉刷新的问题,google不到现成的资料,故此用listview来实现GridView,对ListView而言下拉刷新就很多资料可参考了,这里就不再啰嗦了。

ListViewAdapter.java

package com.example.grideview;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

public class ListViewAdapter extends BaseAdapter {
	private List list;
	private Context context;

	public ListViewAdapter(Context context) {
		this.context = context;
	}

	public void setData(List list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		// 每列两项
		if (list.size() % 2 == 0) {
			return list.size() / 2;
		}

		return list.size() / 2 + 1;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder viewHolder = null;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = View.inflate(context, R.layout.main, null);
			viewHolder.button1 = (Button) convertView
					.findViewById(R.id.imageview1);
			viewHolder.button2 = (Button) convertView
					.findViewById(R.id.imageview2);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		//position计算  两列的情况下:position* 2 +1 多列依次类推 
		//第一列
		String string1 = list.get(position * 2);

		viewHolder.button1.setText(string1);
		viewHolder.button1.setTag(string1);

		viewHolder.button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Log.d("PAGE", v.getTag().toString());
			}
		});
		//position计算  两列的情况下:position* 2 +1 多列依次类推 
		//第二列
		if ((position * 2 + 1) < list.size()) {
			String string2 = list.get(position * 2 + 1);
			viewHolder.button2.setText(string2);
			viewHolder.button2.setTag(string2);
			viewHolder.button2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					Log.d("PAGE", v.getTag().toString());
				}
			});
		} else {
			//此处可以用一张透明图片替换 避免Grid布局混乱
			viewHolder.button2.setVisibility(View.GONE);
		}
		return convertView;
	}

	class ViewHolder {

		private Button button1;
		private Button button2;

	}

}

其余代码就不贴了。可在此处下载 Demo。



你可能感兴趣的:(Android)