首页 > 代码库 > 解决GridView动态设置宽高导致第一个item点击不响应或显示不正常问题

解决GridView动态设置宽高导致第一个item点击不响应或显示不正常问题

最近做项目的时候遇到了2次这个问题,现在分享一下经验

一、问题

问题代码:

</pre><p><pre name="code" class="java">@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final ViewHolder holder;
		final Light light = beans.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.lo_light_item, null);
			holder.tvName = (TextView) convertView
					.findViewById(R.id.tv_light_item);
			holder.image = (ImageView) convertView
					.findViewById(R.id.iv_light_item);
			holder.ly = (LinearLayout) convertView
					.findViewById(R.id.ly_light_item);

			
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		<pre name="code" class="java">// 设置单个item宽高
			holder.ly
					.setLayoutParams(new GridView.LayoutParams(
							WindowManager.LayoutParams.FILL_PARENT, gv
									.getHeight() / 4));
return convertView;}


具体症状

1、第一个Item的View显示不全,总是显示一半,其他的Item没有问题,如论怎么设置都没用

2、第一个Item里面设置的点击事件不管用,但是轻轻的滚动一下点击事件立马就生效了。 

解决办法:

<pre name="code" class="java">@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final ViewHolder holder;
		final Light light = beans.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.lo_light_item, null);
			holder.tvName = (TextView) convertView
					.findViewById(R.id.tv_light_item);
			holder.image = (ImageView) convertView
					.findViewById(R.id.iv_light_item);
			holder.ly = (LinearLayout) convertView
					.findViewById(R.id.ly_light_item);

			// 设置单个item宽高
			holder.ly
					.setLayoutParams(new GridView.LayoutParams(
							WindowManager.LayoutParams.FILL_PARENT, gv
									.getHeight() / 4));
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		return convertView;
	}




解决GridView动态设置宽高导致第一个item点击不响应或显示不正常问题