如何设置从网页URL图像按钮资源在Android的? [英] How to set image button resource from web url in Android?

查看:131
本文介绍了如何设置从网页URL图像按钮资源在Android的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形象的按钮,并想从互联网网址设置背景图片。我不希望保存背景图片到SD卡,而不是我的形象按钮的图像需要被URL。我怎样才能做到这在Android中

I have an image button and would like to set background image from internet URL. I don't want to save background picture into SD card instead my image button's image needs to be URL. How can I do that in Android

推荐答案

试试这个

        Bitmap bitmap;
class loadImage extends AsyncTask<Void , Void, Void>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... params) {
        URL url = new URL(stringURL);
        URI uri = new URI(url.getProtocol(), url.getHost(),
                url.getPath(), url.getQuery(), null);
        HttpURLConnection connection = (HttpURLConnection) uri
                .toURL().openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len = 0;
        while ((len = input.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        byte[] img = byteBuffer.toByteArray();
        byteBuffer.flush();
        byteBuffer.close();
        input.close();
        bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ImageButton image_btn = (ImageButton)findViewById(R.id.your_image_button_id);
        image_btn.setImageBitmap(bitmap);
    }
}

这篇关于如何设置从网页URL图像按钮资源在Android的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆