Skip to content Skip to sidebar Skip to footer

How To Update The Selector(statelistdrawable) Images Using Picasso

I want to load a two images from their own url using picasso and use them as a statelist like:

Solution 1:

I think you can't write to drawable folder of apk at runtime. But you can do what you want dynamically in code.

# Convert Picasso's Bitmap to Drawable
Drawable d = new BitmapDrawable(getResources(),bitmap); 

#Create StateListDrawable
StateListDrawable stateList = new StateListDrawable();
        stateList.addState(newint[] {android.R.attr.state_pressed},drawable1);
        stateList.addState(newint[] {android.R.attr.state_focused},drawable2);

#Add Background
MyButton.setBackgroundDrawable(stateList);

Use code on following lines to get the BitMap from Picasso.

//To Load image from PicassoprivateTarget target = newTarget() {
      @OverridepublicvoidonBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {       
      }
      @OverridepublicvoidonBitmapFailed() {
      }
}

privatevoidsomeMethod() {
   Picasso.with(this).load("url").into(target);
}

@OverridepublicvoidonDestroy() {  // could be in onPause or onStopPicasso.with(this).cancelRequest(target);
   super.onDestroy();
}

Solution 2:

Thanks to Maddy final code looks like this:

        final StateListDrawable stateListDrawable = newStateListDrawable();
        final Picasso picasso = Picasso.with(this.context);
         // selected and checked state
        target_selected = newTarget() {
            @OverridepublicvoidonBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Drawable drawImage = newBitmapDrawable(context.getResources(), bitmap);
                stateListDrawable.addState(new int[]{android.R.attr.state_selected}, drawImage);
                stateListDrawable.addState(new int[]{android.R.attr.state_activated}, drawImage);
            }

            @OverridepublicvoidonBitmapFailed(Drawable errorDrawable) {

            }

            @OverridepublicvoidonPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        picasso.load(context.getString(R.string.server_address_http) + dItem.getIconSelected())
               .into(target_selected);
        target_normal = newTarget() {
            @OverridepublicvoidonBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Drawable drawImage = newBitmapDrawable(context.getResources(), bitmap);
                stateListDrawable.addState(StateSet.WILD_CARD, drawImage);
            }

            @OverridepublicvoidonBitmapFailed(Drawable errorDrawable) {

            }

            @OverridepublicvoidonPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        picasso.load(context.getString(R.string.server_address_http) + dItem.getIconNormal())
               .into(target_normal);
        drawerHolder.icon.setImageDrawable(stateListDrawable);

Post a Comment for "How To Update The Selector(statelistdrawable) Images Using Picasso"