动态添加图像到Android WheelView

时间:2016-02-29 03:35:10

标签: android android-adapter

我几天来一直在研究这个问题。我正在使用kankan Android wheel示例/库,但我想在按下按钮时动态地将图像添加到滚轮。添加的图像取决于按钮的文字。这似乎是一项相当容易的任务,但也许我错过了一些东西。我尝试在传递并将所选图像添加到适配器的缓存图像列表后调用适配器的notifyDataChangedEvent()。调试显示图像被添加到图像列表中,但它们没有显示在方向盘上。如果有人能帮我解决这个问题,我将不胜感激!

代码:

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)));
    }
}

1 个答案:

答案 0 :(得分:0)

由于您返回的计数引用items变量,但addImage函数未更改items大小。尝试更改下面的代码并再次测试:

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