来自URL的StateListDrawable drawables

时间:2015-10-17 09:49:15

标签: android android-drawable android-image statelistdrawable

我试图用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 个答案:

答案 0 :(得分:1)

  1. android.R.attr.state_pressed,android.R.attr.state_selected表示按下并选中,删除已选中并重试 2.交换关闭和关于drawable 3.使用diffenent imageName

     String imageName = "src";