来自 URL 的 StateListDrawable 可绘制对象

StateListDrawable drawables from URL

我正在尝试制作一个带有 StateListDrawable 但带有 2 个远程图像的按钮。

我正在这样尝试:

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

    }
}

但它不起作用...显示关闭图像,但如果我单击按钮则不会显示打开图像。

  1. android.R.attr.state_pressed,android.R.attr.state_selected的意思是按下选中,去掉选中再试 2.try 交换关闭和打开的可绘制对象 3.try 使用不同的图像名称

     String imageName = "src";