Search code examples
androidandroid-drawableandroid-imagestatelistdrawable

StateListDrawable drawables from URL


I'm trying to make a button with StateListDrawable but with 2 remote images.

I'm trying like this :

package com.mylisabox.common.helpers;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;

import java.io.InputStream;
import java.net.URL;

/**
 * Created by jaumard on 16/10/2015.
 */
public class RemoteStateListDrawable extends StateListDrawable
{
    Drawable drawableOn;
    Drawable drawableOff;

    public RemoteStateListDrawable(String urlOn, String urlOff)
    {
        loadImageAsDrawable(urlOff, false);
        loadImageAsDrawable(urlOn, true);
    }

    @Override
    protected boolean onStateChange(int[] stateSet)
    {
        return super.onStateChange(stateSet);
    }

    @Override
    public boolean isStateful()
    {
        return true;
    }

    public void loadImageAsDrawable(final String url, final boolean isOnState)
    {
        new AsyncTask<Void, Void, Drawable>()
        {

            @Override
            protected Drawable doInBackground(Void... params)
            {
                try
                {
                    // open the stream
                    InputStream is = new URL(url).openStream();
                    String imageName = "src";
                    Drawable draw = Drawable.createFromStream(is, imageName);
                    return draw;
                }
                catch (Exception e)
                {
                    // something went wrong
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Drawable drawable)
            {
                super.onPostExecute(drawable);
                if (isOnState)
                {
                    drawableOn = drawable;
                    addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_selected}, drawableOn);

                }
                else
                {
                    drawableOff = drawable;
                    addState(new int[]{}, drawableOff);
                }
            }
        }.execute();

    }
}

But it's not working... The off image was show but never the on image if I click on the button.


Solution

    1. android.R.attr.state_pressed, android.R.attr.state_selected is mean pressed and selected , remove selected and try again 2.try to exchange the off and on drawable 3.try to use diffenent imageName

       String imageName = "src";