2019独角兽企业重金招聘Python工程师标准>>>
在使用网格视图(GridView)时,首先需要在屏幕上添加GridView组件,通常使用
GridView组件所支持的属性如下:
属性 | 描述 |
columnWidth | 设置列的宽度 |
gravity | 设置对齐方式 |
horizintalSpaing | 设置各元素之间的水平间距 |
numColumns | 设置列数,大于1的常数 |
stretchMode | 拉伸模式 |
verticalSpacing | 设置各元素之间的垂直间距 |
GridVew和ListVew类似,需要通过Adapter来提供需要显示的数据。
如图:我们需要使用Grid实现如下的效果(即一个图片和一个标题):
首先,添加主页面的XML布局:
其次,每个表格的布局,即一个图片和一个文本
每项的信息实体:
public class MyGridViewItemInfo {
private int imgId;
private String title;
public int getImgId() {
return imgId;
}
public void setImgId(int imgId) {
this.imgId = imgId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
自定义Adapter:
public class MyGridViewAdapter extends BaseAdapter{
private final List infos = new ArrayList();
private Context context;
public MyGridViewAdapter(Context context,List infos){
this.infos.clear();
this.infos.addAll(infos);
this.context = context;
}
@Override
public int getCount() {
return this.infos.size();
}
@Override
public Object getItem(int arg0) {
return this.infos.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(int arg0, View view, ViewGroup arg2) {
if(view == null){
View view2 = LayoutInflater.from(this.context).inflate(R.layout.grid_view_item, null);
MyGridViewItemInfo info = (MyGridViewItemInfo)this.getItem(arg0);
ImageView imageView = (ImageView)view2.findViewById(R.id.imgView);
imageView.setImageResource(info.getImgId());
TextView textView = (TextView)view2.findViewById(R.id.imgTitle);
textView.setText(info.getTitle());
return view2;
}
return view;
}
}
最后:
public class MyGridViewAvtivity extends Activity {
private final int[] imageleds = new int[] { R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04,
R.drawable.img05, R.drawable.img06, R.drawable.img07, R.drawable.img08, R.drawable.img09, R.drawable.img10,
R.drawable.img11, R.drawable.img12, R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04,
R.drawable.img05, R.drawable.img06, R.drawable.img07, R.drawable.img08, R.drawable.img09, R.drawable.img10,
R.drawable.img11, R.drawable.img12 };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
final GridView gridView = (GridView) findViewById(R.id.gridView);
List infos = new ArrayList();
for (int i = 0; i < imageleds.length; i++) {
MyGridViewItemInfo info = new MyGridViewItemInfo();
info.setImgId(imageleds[i]);
info.setTitle("这是标题" + i);
infos.add(info);
}
MyGridViewAdapter adapter = new MyGridViewAdapter(this, infos);
gridView.setAdapter(adapter);
}
}