0

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

3 回答 3

1

我使用下一个代码来获取位图,一个重要的事情是有时您无法获取 InputStream,即为空,如果发生这种情况,我会尝试 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;
}
于 2013-06-14T23:01:59.960 回答
0

试试这个代码:

Bitmap bmpbtn = loadBitmap(yoururl);

button1.setImageBitmap(bmpbtn);
于 2013-06-15T04:44:49.147 回答
0

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

于 2013-06-14T23:03:51.293 回答