Android常用控件之GridView使用BaseAdapter

时间:2022-08-31 22:43:59

    我们可以为GridView添加自定义的Adapter,首先看下用自定义Adapter的显示效果

Android常用控件之GridView使用BaseAdapter

在布局文件main.xml文件中定义一个GridView控件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >


<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:stretchMode="columnWidth" >
</GridView>

</RelativeLayout>

要使用BaseAdapter首先定义一个类继承BaseAdapter,并重写几个方法

package com.example.gridviewadapterdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

private GridView gridView = null;
private int[] imageId = new int[] { R.drawable.img01, R.drawable.img02,
R.drawable.img03, R.drawable.img04, R.drawable.img05,
R.drawable.img06, R.drawable.img07, R.drawable.img08,
R.drawable.img09, R.drawable.img10, R.drawable.img11,
R.drawable.img12, }; // 定义并初始化保存图片id的数组

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

gridView = (GridView) findViewById(R.id.gridView);
GridViewAdapter gridViewAdapter = new GridViewAdapter();
gridView.setAdapter(gridViewAdapter);
// 为GridView设定监听器
gridView.setOnItemClickListener(new gridViewListener());
}

class gridViewListener implements OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("arg2 = " + arg2); // 打印出点击的位置
}
}

private class GridViewAdapter extends BaseAdapter {

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview; // 声明ImageView的对象
if (convertView == null) {
imageview = new ImageView(MainActivity.this); // 实例化ImageView的对象
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE); // 设置缩放方式
imageview.setPadding(5, 0, 5, 0); // 设置ImageView的内边距
} else {
imageview = (ImageView) convertView;
}
imageview.setImageResource(imageId[position]); // 为ImageView设置要显示的图片
return imageview; // 返回ImageView
}

/*
* 功能:获得当前选项的ID
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
//System.out.println("getItemId = " + position);
return position;
}

/*
* 功能:获得当前选项
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem(int position) {
return position;
}

/*
* 获得数量
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return imageId.length;
}
}

}

样例代码

点击打开链接