将位图设置为我的布局背景

Set Bitmap to my layout background

我正在从 URL 下载图像并将此位图用于我的布局背景。我看不到我的图像。

过去两天我一直在为此苦苦挣扎。现在我仍然无法找到解决方案。我用谷歌搜索了很多。请帮我弄错我做的错误。

非常感谢。

我的代码:

Bitmap myImage = getBitmapFromURL("http://looksok.files.wordpress.com/2011/12/me.jpg");


        if (android.os.Build.VERSION.SDK_INT >= 16){
            setBackgroundV16Plus( myImage);
        }
        else{
            setBackgroundV16Minus( myImage);
        }

@TargetApi(16)
    private void setBackgroundV16Plus(  Bitmap bitmap) {
        linearLayout.setBackground(new BitmapDrawable(getApplicationContext().getResources(), bitmap));

    }

    @SuppressWarnings("deprecation")
    private void setBackgroundV16Minus(  Bitmap bitmap) {
        linearLayout.setBackgroundDrawable(new BitmapDrawable(bitmap));
    }

    public Bitmap getBitmapFromURL(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
RelativeLayout relative = (RelativeLayout) findViewById(R.id.relative1);
Drawable dr = new BitmapDrawable(bit);
(view).setBackgroundDrawable(drawable);

要连接到互联网,您必须使用 Thread 或 Async Task

public class MyAyncTask extends AsyncTask<Void, Void,Void>{

    @Override
    protected Void doInBackground(Void... params) {
        Bitmap myImage = getBitmapFromURL("http://looksok.files.wordpress.com/2011/12/me.jpg");
        return null;
    }
}

使用picasso库,好用 这是 link 的毕加索示例

http://javatechig.com/android/how-to-use-picasso-library-in-android

private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    public LoadProfileImage() {

    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap bitmap = null;
        try {
            InputStream in = new URL(urldisplay).openStream();
            bitmap = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.println(Log.ASSERT, "error", "" + e);
            e.printStackTrace();
        }
        return bitmap;
    }

    protected void onPostExecute(Bitmap result) {
     myImage=result;
    }
}

下载图片的调用方法

 new LoadProfileImage().execute("http://looksok.files.wordpress.com/2011/12/me.jpg");

此语句下载图像并存储到您的位图变量现在设置背景

并在清单上添加互联网权限。