最新消息:code4apk全新上线,专注于android代码分享,android源码下载,打造专业的android学习分享平台!

Android GridView的使用

android教程 admin 2307浏览 0评论

Android的GridView控件用于把一系列的空间组织成一个二维的网格显示出来应用的比较多的就是组合图片显示下面我就详细讲一个例子

1、 首先写一个类继承BaseAdapter
[java]
package com.yarin.android.Examples_04_19;

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

public class ImageAdapter extends BaseAdapter
{
// 定义Context
private Context mContext;
// 定义整型数组 即图片源
private Integer[] mImageIds =
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7,
R.drawable.img8,
R.drawable.img1,
};

public ImageAdapter(Context c)
{
mContext = c;
}

// 获取图片的个数
public int getCount()
{
return mImageIds.length;
}

// 获取图片在库中的位置
public Object getItem(int position)
{
return position;
}

// 获取图片ID
public long getItemId(int position)
{
return position;
}

public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
// 给ImageView设置资源
imageView = new ImageView(mContext);
// 设置布局 图片120×120显示
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
// 设置显示比例类型
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
else
{
imageView = (ImageView) convertView;
}

imageView.setImageResource(mImageIds[position]);
return imageView;
}

}
[/java]
2、 定义一个Activity

package com.yarin.android.Examples_04_19;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Activity01 extends Activity
{
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//取得GridView对象
		GridView gridview = (GridView) findViewById(R.id.gridview);
		//添加元素给gridview
		gridview.setAdapter(new ImageAdapter(this));

		// 设置Gallery的背景
		gridview.setBackgroundResource(R.drawable.bg0);

		//事件监听
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id)
			{
				Toast.makeText(Activity01.this, "你选择了" + (position + 1) + " 号图片", Toast.LENGTH_SHORT).show();
			}
		});
	}
}

3、 XML配置文件

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

文章来自: http://www.oschina.net/code/snippet_16_3069#4542

转载请注明:回车桌面 » Android GridView的使用

您必须 登录 才能发表评论!