最近在android项目中,遇到需要动态设置GridView列数的问题,实现如下:
首先大体估算一下item宽度(这里估计宽度100,然后计算满屏能显示几个item):
GridView hotGrid = (GridView) findViewById(R.id.hot_word_grid);
int colnum = ZETTool.getScreenWith(HomeSearchActivity.this) / 100;
hotGrid.setNumColumns(colnum);
在Adapter getView方法中:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView wordTV;
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.hot_word_item,null);
wordTV = (TextView)convertView.findViewById(R.id.grid_hot_word_tv);
convertView.setTag(wordTV);
}else {
wordTV = (TextView)convertView.getTag();
}
HotWordsModel.ContractRootModel.BusContModel.KeywordListModel model = dataList.get(position);
wordTV.setText(model.getContent());
// 根据列数计算项目宽度,以使总宽度尽量填充屏幕
int itemWidth = (ZETTool.getScreenWith((Activity) context) - colnum * 10) / colnum;
AbsListView.LayoutParams param = new AbsListView.LayoutParams(
itemWidth,
AbsListView.LayoutParams.WRAP_CONTENT);
convertView.setLayoutParams(param);
return convertView;
}
附上效果图
版权声明:本文为smk524198002原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。