我的应用程序中有一个 GridView,它在几乎所有设备上都非常棒,但是......我给一些朋友测试,他们说我的应用程序在 GridView 上崩溃了。. 应用程序崩溃或者他们真的必须滚动它小心。有朋友说GridView还可以(还有我的——HTC Wildfire、三星Galaxy Mini),但是我有三星Galaxy S3、S4的朋友却说它崩溃了。我的网格视图:
public static List<Item> items = new ArrayList<Item>();
...
GridView gridView = (GridView) findViewById(R.id.gridview);
items.clear();
//add all items to list
gridView.setAdapter(new ImageAdapter(this, items));
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
图像适配器:
public class ImageAdapter extends BaseAdapter {
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public ImageAdapter(Context context, List<Item> items) {
inflater = LayoutInflater.from(context);
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return items.get(i).drawable;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = inflater.inflate(R.layout.squareimageview, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = (Item) items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
return v;
}
}
我的 SquareImageView 类,它将我的 GridView 的元素大小设置为 2 列并在多个屏幕上看起来不错:
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}