除了listview会使用适配器外,还有一种就是GridView,listview是单列多行的显示形式,适用于多项目的查看。而GridView是多行多列的显示形式,一般用在查看图片样式的activity中。一个小demo。每一项都是一个图片下面一行文字。
GirdView的一些属性:
android:numColumns="auto_fit" --------列数设置为自动
android:columnWidth="90dp",----------每列的宽度,也就是Item的宽度
android:stretchMode="columnWidth"------缩放与列宽大小同步
android:verticalSpacing="10dp"----------垂直边距
android:horizontalSpacing="10dp"-------水平边距
这里使用自定义适配器,
GridViewActivity
public class GridViewActivity extends Activity { private GridView gridView; private GridViewAdapter adapter; private List<Map<String,Object>> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid_view); gridView = (GridView)findViewById(R.id.gridView); list = new ArrayList<Map<String, Object>>(); adapter = new GridViewAdapter(this,getData()); gridView.setAdapter(adapter); }
GridViewAdapter
在这里有一个比较重要的就是设置gridview的行高,
convertView.setLayoutParams(new GridView.LayoutParams(100, 100));//重点行
但是这个属性android:columnWidth不知道为什么不能起作用。无论设置多少都不变化
class GridViewAdapter extends BaseAdapter{ private LayoutInflater mLayoutIntfalter; private Context context; private List<Map<String,Object>> list; public GridViewAdapter(Context context,List<Map<String,Object>> list){ this.context = context; this.list = list; this.mLayoutIntfalter = LayoutInflater.from(context); } @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) { ViewHold viewHold=null; if(convertView == null){ viewHold = new ViewHold(); convertView = mLayoutIntfalter.inflate(R.layout.gridviewitemlayout,null); viewHold.image =(ImageView)convertView.findViewById(R.id.imageView2); viewHold.textView = (TextView)convertView.findViewById(R.id.textView4); convertView.setTag(viewHold); }else{ viewHold =(ViewHold) convertView.getTag(); } int id = Integer.parseInt(list.get(position).get("pic").toString()); viewHold.image.setImageResource(id); viewHold.textView.setText(list.get(position).get("titel").toString()); convertView.setLayoutParams(new GridView.LayoutParams(100, 100));//重点行 return convertView; } public final class ViewHold{ public ImageView image; public TextView textView; }
gridviewitemlayout.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"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView2" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/textView4" /> </LinearLayout>
原文:http://www.cnblogs.com/techdreaming/p/4934541.html