1.介绍
就是GridView组件的应用!九宫格什么的都可以通过这个组件实现。
2.效果图
3.XML文件
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:id="@+id/gridview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="auto_fit" android:columnWidth="100sp" android:stretchMode="columnWidth" android:gravity="center" /> </FrameLayout>
4.Java代码
package wei.ye.g1; import android.app.Activity; import android.content.Context; 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 Wangge extends Activity { private static int[] images = { R.drawable.baos, R.drawable.caoc, R.drawable.chenyj, R.drawable.chenyy, R.drawable.gouj, R.drawable.guany, R.drawable.hanx, R.drawable.lp, R.drawable.liub, R.drawable.qinq, R.drawable.tiemz, R.drawable.wus, R.drawable.xiangy, R.drawable.yuef, R.drawable.zhaoky, R.drawable.zhugl, R.drawable.xis, R.drawable.yingz }; GridView gv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.wangge); setTitle("网格视图"); gv = (GridView) findViewById(R.id.gridview); gv.setAdapter(new ImageAdapter(this)); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } @Override public int getCount() { return images.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } // 创建一个ImageView,并设定对应的图片.images 就是需要显示的图片 public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; // System.out.println(convertView); // if -- else 为了节省内存空间,减少对象的创建 if (convertView == null) { imageView = new ImageView(mContext); //设置显示图片的大小 imageView.setLayoutParams(new GridView.LayoutParams(120, 120)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(images[position]); return imageView; } } }