在GridView中动态绘制图像

时间:2012-01-18 11:46:18

标签: android image bitmap baseadapter

我有这个类在GridView中绘制图像:

    public class ImageAdapter extends BaseAdapter
{
   Context MyContext;
   Vector<User> users;
   int level;


   public ImageAdapter(Context _MyContext, Vector<User> _users, int _level)
   {
      MyContext = _MyContext;
      users = _users;
      level = _level;
   }

   @Override
   public int getCount() 
   {
                     /* Set the number of element we want on the grid */
       if(users==null)
           return 0;
      return users.size();
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) 
   {
      View MyView = convertView;            
                             /*we define the view that will display on the grid*/
         //Inflate the layout
         LayoutInflater li = getLayoutInflater();
         MyView = li.inflate(R.layout.grid_item, null);

         // Add The Text!!!
         TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);

         // Add The Image!!!           
         ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
         iv.setBackgroundResource(R.drawable.button_restricted);
         iv.setImageResource(R.drawable.defaultperson02);
         byte[] bytes;
         if(position<users.size()){
             final User user =users.get(position);
            tv.setText(users.get(position).getDisplay_name());  
            bytes = user.getAvatar();
            if(bytes!=null && bytes.length>0 ){
                try{
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    iv.setImageBitmap(bitmap);
                }catch(Exception e){                        

                }
            }

         }

      return MyView;
   }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }
}

这个课程通常很有效,但有时我会得到这个例外:

01-18 12:39:26.160: ERROR/AndroidRuntime(30496): FATAL EXCEPTION: main
01-18 12:39:26.160: ERROR/AndroidRuntime(30496): java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=15303KB, Allocated=10747KB, Bitmap Size=18391KB)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:625)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:638)

我尝试过回收位图,但错误仍然存​​在。

你知道为什么我有这个问题吗?

1 个答案:

答案 0 :(得分:0)

您必须重用convertview类。您在上面的代码中所做的是在每次调用getView时创建一个新视图。这不是正确的做事方式。而是检查convertview是否为null。如果它为null则膨胀视图,否则重用convertview。有关详细信息,请查看this