Add Gallery images dynamically in android

前端 未结 2 1976
逝去的感伤
逝去的感伤 2021-02-11 08:33

I\'ve done Gallery of images displayed on emulator by static(i.e images from drawable folder).Now i need to add some images into the list of gallery, dynamically fr

2条回答
  •  醉梦人生
    2021-02-11 08:51

    In your case, you can try make your image array a dynamic list, ex: ArrayList. Upon the arrival of new item, add it to the list, and call notifyDataSetChanged() (method of the adapter), and your gallery list will be refreshed.

    Depends on your case, I found that it is better to use AsyncTask here to update the list, and call notifyDataSetChanged.

    The adapter class would looks similarly to this

    public class AddImgAdp extends BaseAdapter {
        int GalItemBg;
        ArrayList bitmapList;
        private Context cont;
    
        public AddImgAdp(Context c, ArrayList bitmapList) {
            cont = c;
            TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
            GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
            typArray.recycle();
            this.bitmapList = bitmapList;
        }
    
        public int getCount() {
            return bitmapList.size();
        }
    
        public Object getItem(int position) {
            return bitmapList.get(position);
        }
    
        public long getItemId(int position) {
            return bitmapList.get(position);
        }
    
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imgView = new ImageView(cont);
    
            // imgView.setImageResource(Imgid[position]);
            imgView.setImageBitmap(bitmapList.get(position));
    
            imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
            imgView.setScaleType(ImageView.ScaleType.FIT_XY);
            imgView.setBackgroundResource(GalItemBg);
    
            return imgView;
        }
    }
    

    Let me know if any errors, I am way to depending on IDE.

提交回复
热议问题