【问题标题】:Set button background image from url从 url 设置按钮背景图片
【发布时间】:2013-06-14 22:41:02
【问题描述】:

我想知道如何从 android 上的 URL 设置按钮背景图像。 如果您需要知道,按钮 ID 为蓝色。

我试过了,但是没用。

    public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
    in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
    copy(in, out);
    out.flush();

    final byte[] data = dataStream.toByteArray();
    BitmapFactory.Options options = new BitmapFactory.Options();
    //options.inSampleSize = 1;

    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
    Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
    closeStream(in);
    closeStream(out);
    }

    return bitmap;
    }

【问题讨论】:

  • 如果你想有效地做到这一点,看看这个goo.gl/i15Yn

标签: android eclipse button background-image


【解决方案1】:

我使用了下一段代码来获取位图,一个重要的事情是有时你无法获取InputStream,那就是null,如果发生这种情况我会尝试3次。

public Bitmap generateBitmap(String url){
    bitmap_picture = null;

    int intentos = 0;
    boolean exception = true;
    while((exception) && (intentos < 3)){
        try {
            URL imageURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
            conn.connect();
            InputStream bitIs = conn.getInputStream();
            if(bitIs != null){
                bitmap_picture = BitmapFactory.decodeStream(bitIs);
                exception = false;
            }else{
                Log.e("InputStream", "Viene null");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            exception = true;
        } catch (IOException e) {
            e.printStackTrace();
            exception = true;
        }
        intentos++;
    }

    return bitmap_picture;
}

【讨论】:

    【解决方案2】:

    不要直接在 UI(主)线程中加载图像,因为它会在加载图像时使 UI 冻结。而是在单独的线程中执行此操作,例如使用AsyncTask。 AsyncTask 将让图像在其doInBackground() 方法中加载,然后可以在onPostExecute() 方法中将其设置为按钮背景图像。看到这个答案:https://stackoverflow.com/a/10868126/2241463

    【讨论】:

      【解决方案3】:

      试试这个代码:

      Bitmap bmpbtn = loadBitmap(yoururl);
      
      button1.setImageBitmap(bmpbtn);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 2011-04-07
        • 1970-01-01
        相关资源
        最近更新 更多