在Android应用程序中使用gridview显示图像

时间:2012-07-05 18:58:23

标签: android

我在gridview中尝试了许多用于显示图像的代码,但应用程序在模拟器中已经关闭了。这是我的代码......

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);        
    final GridView ObjGrid = (GridView)findViewById(R.id.gridview);
    ObjGrid.setAdapter(new ImageAdapter(this));        
}

ImageAdapter类如上所述

public class ImageAdapter extends BaseAdapter {

int[] images = new int[]{
        R.drawable.pic1,
        R.drawable.pic2,
        R.drawable.pic3,
        R.drawable.pic4,
        R.drawable.pic5,
        R.drawable.pic6
    };
private Context cont;
public ImageAdapter(Context applicationContext) {
    cont = applicationContext;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return images.length;
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public View getView(int arg0, View ConvertView, ViewGroup arg2) {
    ImageView iv;
    if(ConvertView == null)
    {
        iv = new ImageView(cont);
        iv.setLayoutParams(new GridView.LayoutParams(180, 180));
        iv.setScaleType(ScaleType.CENTER_CROP);
        iv.setPadding(0, 8, 8, 8);          
    }
    else
    {           
        iv=(ImageView)ConvertView;
    }
    iv.setImageResource(images[arg0]);
    return null;
}

}

请给我解决方案,如果有可能将项目文件提供给下载,那么对我来说将是非常有帮助的... 谢谢

1 个答案:

答案 0 :(得分:2)

您在getView方法中返回null。您应该返回视图(在您的情况下,您正在生成的ImageView),而不是null!