2016-02-29 118 views
1

我一直在這個問題上工作了好幾天了。我正在使用kankan Android輪子示例/庫,但我想在按下按鈕時動態地將圖像添加到輪子。添加的圖像取決於按鈕的文本。這似乎是一個相當簡單的任務,但也許我錯過了一些東西。在傳遞並將選定圖像添加到適配器的緩存圖像列表後,我嘗試調用適配器的notifyDataChangedEvent()。調試顯示圖像被添加到圖像列表中,但它們沒有顯示在輪子上。如果有人可以請幫我解決這個問題,我將不勝感激!動態添加圖像到Android WheelView

代碼:

public void addItem(String text) { 

    for(Item c: Item.values()){ 
     if(c.getName().equals(text)) { 
      slotMachineAdapter.addImage(c.getImage()); 
      break; 
     } 
    } 
    slotMachineAdapter.notifyDataChangedEvent(); 
} 

適配器

private class SlotMachineAdapter extends AbstractWheelAdapter { 
    // Image size 
    final int IMAGE_WIDTH = 700; 
    final int IMAGE_HEIGHT = 150; 

    // Slot machine symbols 
    private final int items[] = new int[] { 
      R.mipmap.ic_flipper 
    }; 

    // Cached images 
    private List<SoftReference<Bitmap>> images; 

    // Layout inflater 
    private Context context; 

    /** 
    * Constructor 
    */ 
    public SlotMachineAdapter(Context context) { 
     this.context = context; 
     images = new ArrayList<SoftReference<Bitmap>>(); 
     for (int id : items) { 
      images.add(new SoftReference<Bitmap>(loadImage(id))); 
     } 
    } 

    /** 
    * Loads image from resources 
    */ 
    private Bitmap loadImage(int id) { 
     Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id); 
     Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true); 
     bitmap.recycle(); 
     return scaled; 
    } 

    @Override 
    public int getItemsCount() { 
     return items.length; 
    } 

    // Layout params for image view 
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT); 

    @Override 
    public View getItem(int index, View cachedView, ViewGroup parent) { 
     ImageView img; 
     if (cachedView != null) { 
      img = (ImageView) cachedView; 
     } else { 
      img = new ImageView(context); 
     } 
     img.setLayoutParams(params); 
     SoftReference<Bitmap> bitmapRef = images.get(index); 
     Bitmap bitmap = bitmapRef.get(); 
     if (bitmap == null) { 
      bitmap = loadImage(items[index]); 
      images.set(index, new SoftReference<Bitmap>(bitmap)); 
     } 
     img.setImageBitmap(bitmap); 

     return img; 
    } 

    //Adds image to list of images 
    public void addImage(int img){ 
     images.add(new SoftReference<Bitmap>(loadImage(img))); 
    } 
} 

回答

0

因爲您返回參考items變量,但addImage功能並沒有改變items大小計數。嘗試更改您的代碼,如下所示,然後再次測試:

@Override 
    public int getItemsCount() { 
     return images.size(); 
    } 
+0

我知道這會很容易!我覺得很愚蠢。非常感謝John Steve – Elli

+0

當如此疲憊時,休息一下,一切都會好起來的:D – NamNH