1

我想使用StateListDrawable,但與2遠程圖像使一個按鈕。StateListDrawable從URL的繪製

我想是這樣的:

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
  1. android.R.attr.state_pressed,android.R.attr.state_selected是平均壓和選擇,刪除選定的,然後再試一次 2.try交換和關閉繪製 3.try使用diffenent imageName

    String imageName = "src"; 
    
+0

這是工作,我有兩個狀態正出現,但是我還有一個問題,握拳時的圖像是可見它的扭曲,但如果我點擊圖像變得偉大。這只是第一次。我想因爲圖像是異步加載的...我該如何解決這個問題的想法? – jaumard

+0

如果它導致加載異步,您可以在加載完成之前添加默認img。 –