我有一个网格视图,这就是我实现它的方式
<GridView
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:id="@+id/homeGrid"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:layout_weight="3"
android:numColumns="auto_fit" />
旨在使用自定义适配器显示7个项目,这就是我实现适配器的方式
private Context mContext;
private final String[] item;
private final int[] imageId;
public GridAdapter(Context c, String[] item, int[] imageId) {
mContext = c;
this.item = item;
this.imageId = imageId;
}
@Override
public int getCount() {
return item.length;
}
@Override
public Object getItem(int position) {
return item[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = inflater.inflate(R.layout.home_grid_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
textView.setText(item[position]);
imageView.setImageResource(imageId[position]);
} else {
grid = convertView;
}
return grid;
}
}
然后我在我的活动中启动它
GridAdapter adapter = new GridAdapter(HomePage.this, title, imageId);
GridView grid = (GridView) findViewById(R.id.homeGrid);
问题是应用程序显示位置6的最后位置为位置0,我实际上将onitemclicklistener实现到gridview,当我点击最后一个位置时,我得到了正确的位置。
我的错误在哪里?
答案 0 :(得分:0)
试试这段代码。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.home_grid_layout, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image);
textView.setText(item[position]);
imageView.setImageResource(imageId[position]);
return convertView;
}