2011-03-05 62 views
1

我想填充Android GridView與充氣的視圖,視圖有從數據的ArrayList填充的ImageView和TextView。從資產填充GridView的問題

一切都很好,但是,當我滾動網格時,我的前7項正在重複。

namCont.setAdapter(new ImageAdapter(getApplicationContext())); 

我的代碼:

public class ImageAdapter extends BaseAdapter 
{ 
    private Context mContext; 

    public ImageAdapter(Context c) 
    { 
     mContext = c; 
    } 
    public int getCount() 
    { 
     return kat.namirnice.size(); 

    } 
    public Object getItem(int position) 
    { 
     return position; 
    } 
    public long getItemId(int position) 
    { 
     return position; 
    } 
    public View getView(int position, View convertView, ViewGroup parent) 
    { 
     View view; 
     ImageView imageView = null; 

     if (convertView == null) 
     { 
      view = LayoutInflater.from(mContext).inflate(R.layout.nam_item,null); 
      try 
      { 
       TextView textView = (TextView)view.findViewById(R.id.tekst); 

       imageView = (ImageView)view.findViewById(R.id.slika); 

       textView.setText(kat.namirnice.get(position).naziv); 

       Log.i(TAG, "\n position: " + position); 
       buf = new BufferedInputStream((assetManager.open("images/" + activKat_int + "/" + position + ".png"))); 
       Bitmap bitmap = BitmapFactory.decodeStream(buf); 
       Drawable d = new BitmapDrawable(bitmap); 
       imageView.setImageDrawable(d); 
       buf.close(); 

      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 

     } 
     else 
     { 
      view = convertView; 
     } 

     return view; 
    } 

回答

6

在ListView的意見是回收。所以最終,我想當你到第8個位置時,它會回收它的第一個視圖,並且在你的代碼塊view = convertView;中,你所做的只是返回現有的再循環視圖。

相反,你需要這樣做。

public View getView(int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
      convertView = LayoutInflater.from(mContext).inflate(R.layout.nam_item, 
        null); 
     } 
     try { 
      TextView textView = (TextView) convertView.findViewById(R.id.tekst); 
      ImageView imageView = (ImageView) convertView.findViewById(R.id.slika); 
      textView.setText(kat.namirnice.get(position).naziv); 
      Log.i(TAG, "\n position: " + position); 
      buf = new BufferedInputStream((assetManager.open("images/" 
        + activKat_int + "/" + position + ".png"))); 
      Bitmap bitmap = BitmapFactory.decodeStream(buf); 
      Drawable d = new BitmapDrawable(bitmap); 
      imageView.setImageDrawable(d); 
      buf.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return convertView; 
    } 
+0

非常感謝,它現在正在工作。 – tomihr 2011-03-05 14:15:11