***GridView的基本使用
*定义:
GridView是一个表格显示资源的控件,可以在两个可滚动的方向上显示资源
*基本属性:
android:numColumns="auto_fit" :表示GridView中一行中展示item的列数,auto_fit表示根据手机屏幕的宽度由系统设置比较理想的列数,当然这里也可以指定具体列数
android:columnWidth="80dp" :设置每一列的宽度
android:horizontalSpacing="10dp" : 表示设置列之间的间距
android:verticalSpacing="10dp" :表示设置行之间的间距
*基本使用:和ListView的使用类似
xml布局中:
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/timg1" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
Java代码中:
public class ResultActivity extends Activity {
private GridView gv;
private List<Map<String, Object>> list;
private int[] images = {R.drawable.timg1,R.drawable.timg2,R.drawable.timg3,R.drawable.timg4,R.drawable.timg5,R.drawable.timg6};
//要注意几张图片的大小相同
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
gv = (GridView) findViewById(R.id.gv);
list = new ArrayList<Map<String,Object>>();
for (int i = 0; i < images.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("img", images[i]);
map.put("text", "头像-"+i);
list.add(map);
}
MyBaseAdapter adapter = new MyBaseAdapter();
gv.setAdapter(adapter);
}
class MyBaseAdapter extends BaseAdapter{
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.iv = (ImageView) convertView.findViewById(R.id.imageView1);
holder.tv = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.iv.setImageResource((Integer) list.get(position).get("img"));
holder.tv.setText((CharSequence) list.get(position).get("text"));
return convertView;
}
}
static class ViewHolder{
ImageView iv;
TextView tv;
}
}