Android中GridView的实现实例

实现效果:

Android中GridView的实现实例

activity文件代码:

package com.tmacsky;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MyGridViewActivity extends Activity {
//定义图片数组
private int[] mImages = new int[]{R.drawable.ha,R.drawable.hb,R.drawable.hc,R.drawable.hd,R.drawable.he,R.drawable.hf,R.drawable.hg,R.drawable.hh};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gView = (GridView)findViewById(R.id.gView);
//建立数据源,设置adapter
gView.setAdapter(new ImageAdapter());
}
class ImageAdapter extends BaseAdapter{
public int getCount() {
// TODO Auto-generated method stub
return mImages.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mImages[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return mImages[position];
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(MyGridViewActivity.this);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setPadding(5, 5, 5, 5);
imageView.setImageResource(mImages[position]);
return imageView;
}
}
}

对应gridview.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:horizontalSpacing="2dp"
android:verticalSpacing="2dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:id="@+id/gView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
</LinearLayout>

更多详情参看官方帮助文档里的GridView源码:

Android中GridView的实现实例

上一篇:REST设计规则


下一篇:python第一天