一、问题
1.1 先看问题代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_grid_item, parent, false);
convertView.findViewById(R.id.avatar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity
}
});
}
convertView.setLayoutParams(new GridView.LayoutParams(mWindowWidth / 3, mWidowWidth / 3));
//其他代码
return convertView;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_grid_item, parent, false);
convertView.findViewById(R.id.avatar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity
}
});
}
convertView.setLayoutParams(new GridView.LayoutParams(mWindowWidth / 3, mWidowWidth / 3));
//其他代码
return convertView;
}
代码的目的是希望根据屏幕的宽度动态设置GridView内Item的大小,很自然就这么写了。
1.2 具体症状
1.2.1 第一个Item的ImageView显示不全,总是显示一半,其他的Item没有问题,如论怎么设置都没用
1.2.2 第一个Item里面设置的点击事件不管用,但是轻轻的滚动一下点击事件立马就生效了。
二、解决办法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_grid_item, parent, false);
convertView.setLayoutParams(new GridView.LayoutParams(mWindowWidth / 3, mWindowWidth / 3));
convertView.findViewById(R.id.user_avatar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity
}
});
}
//其他代码
return convertView;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_grid_item, parent, false);
convertView.setLayoutParams(new GridView.LayoutParams(mWindowWidth / 3, mWindowWidth / 3));
convertView.findViewById(R.id.user_avatar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity
}
});
}
//其他代码
return convertView;
}
如上即可。
三、相关文章
Why is changing where layout parameters are set solving my “OnClickListener not working for first item in GridView” issue?
本文转自博客园农民伯伯的博客,原文链接:【Android疑难杂症】GridView动态设置Item的宽高导致第一个Item不响应或显示不正常的问题,如需转载请自行联系原博主。