GridView的最后固定显示一个增加图片,点击图片动态增加内容item

本例子实现在GridView的最后固定显示一个增加图片,点击图片动态增加内容item。

1.main.xml:



    

2.grid_item.xml:




    
3.GridViewAdapter.java:

package com.yayun.gridviewdemo;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class GridViewAdapter extends BaseAdapter {
	private Context context;
	private List list;
	LayoutInflater layoutInflater;
	private ImageView mImageView;

	public GridViewAdapter(Context context, List list) {
		this.context = context;
		this.list = list;
		layoutInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return list.size()+1;//注意此处
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		convertView = layoutInflater.inflate(R.layout.grid_item, null);
		mImageView = (ImageView) convertView.findViewById(R.id.item);
		if (position < list.size()) {
			mImageView.setBackgroundResource(list.get(position));
		}else{
			mImageView.setBackgroundResource(R.drawable.pic3);//最后一个显示加号图片
		}
		return convertView;
	}

}
4.MainActivity.java:
package com.yayun.gridviewdemo;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	private List mDatas;
private GridView mGridView;
private GridViewAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mGridView=(GridView) findViewById(R.id.gv_test);
		
		initDatas();
		adapter=new GridViewAdapter(MainActivity.this,mDatas);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				if(position==parent.getChildCount()-1){
					mDatas.add(R.drawable.pic1);
					Toast.makeText(MainActivity.this, "您点击了添加", 1).show();
					adapter=new GridViewAdapter(MainActivity.this, mDatas);
					mGridView.setAdapter(adapter);
					adapter.notifyDataSetChanged();
				}
				
			}
		});
		
	}
	private void initDatas() {
		mDatas=new ArrayList<>();
		mDatas.add(R.drawable.pic1);
		mDatas.add(R.drawable.pic1);
		mDatas.add(R.drawable.pic1);
		mDatas.add(R.drawable.pic1);
		mDatas.add(R.drawable.pic1);
		
	}

	
	}




你可能感兴趣的:(android)