从网址设置按钮背景图像

时间:2013-06-14 22:41:02

标签: android eclipse button background-image

我想知道如何从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;
    }

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

试试这段代码:

Bitmap bmpbtn = loadBitmap(yoururl);

button1.setImageBitmap(bmpbtn);