[笔记]android UI ------ GridView
GridView按照行列的方式来显示内容,一般适合显示图标、图片等内容,主要用于设置Adapter
在这里主要是基础BaseAdapter类,重写其中的方法,主要是重写getView方法设置图片的显示格式
实例代码如下
GridViewTest.java
1 /* 2 * @author hualang 3 */ 4 package org.hualang.grid; 5 6 import android.app.Activity; 7 import android.content.Context; 8 import android.os.Bundle; 9 import android.view.View; 10 import android.view.ViewGroup; 11 import android.widget.BaseAdapter; 12 import android.widget.GridView; 13 import android.widget.ImageView; 14 15 public class GridViewTest extends Activity { 16 /** Called when the activity is first created. */ 17 private GridView gv; 18 @Override 19 public void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.main); 22 23 //通过findViewById方法获得GridView对象 24 gv=(GridView)findViewById(R.id.GridView01); 25 //设置GridView的行数 26 gv.setNumColumns(4); 27 gv.setAdapter(new MyAdapter(this)); 28 } 29 //自定义适配器 30 class MyAdapter extends BaseAdapter 31 { 32 //图片id数组 33 private Integer[] imgs={ 34 R.drawable.img01, 35 R.drawable.img02, 36 R.drawable.img03, 37 R.drawable.img04, 38 R.drawable.img05, 39 R.drawable.img06, 40 R.drawable.img07, 41 R.drawable.img08, 42 43 R.drawable.img01, 44 R.drawable.img02, 45 R.drawable.img03, 46 R.drawable.img04, 47 R.drawable.img05, 48 R.drawable.img06, 49 R.drawable.img07, 50 R.drawable.img08 51 }; 52 //上下文对象 53 Context context; 54 //构造方法 55 MyAdapter(Context context) 56 { 57 this.context=context; 58 } 59 //获得数量 60 public int getCount() 61 { 62 return imgs.length; 63 } 64 //获得当前选项 65 public Object getItem(int item) 66 { 67 return item; 68 } 69 //获得当前选项id 70 public long getItemId(int id) 71 { 72 return id; 73 } 74 75 //创建View方法 76 public View getView(int position,View convertView,ViewGroup parent) 77 { 78 ImageView imageView; 79 if(convertView==null) 80 { 81 //实例化ImageView对象 82 imageView=new ImageView(context); 83 //设置ImageView对象布局 84 imageView.setLayoutParams(new GridView.LayoutParams(45,45)); 85 //设置边界对齐 86 imageView.setAdjustViewBounds(false); 87 //设置刻度类型 88 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 89 //设置间距 90 imageView.setPadding(8,8,8,8); 91 }else 92 { 93 imageView=(ImageView)convertView; 94 } 95 //为ImageView设置图片资源 96 imageView.setImageResource(imgs[position]); 97 return imageView; 98 } 99 100 } 101 }
main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 > 7 <GridView 8 android:id="@+id/GridView01" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content"></GridView> 11 </LinearLayout>
运行结果如下