Skip to content Skip to sidebar Skip to footer

LinearLayout Background And Images From Web

I gotta extract images from internet and apply them as a LinearLayout's background - is it possible ? I haven't seen any appropriate methods for this yet.

Solution 1:

Sure.

Just get the InputStream of the image:

InputStream is = (InputStream) new URL(url).getContent();

Get the Drawable from the stream:

Drawable d = Drawable.createFromStream(is, "src name");

Then set the LinearLayout Background Drawable:

linearLayout.setBackgroundDrawable(d);

This actually sets the image directly from the stream. You may want to use an ASyncTask to pull down the drawable in the background and set it afterwards: http://developer.android.com/reference/android/os/AsyncTask.html

You may want to research lazy loaders as well: http://evancharlton.com/thoughts/lazy-loading-images-in-a-listview


Solution 2:

Simply load your image with BitmapFactory, (resize it if needed), use BitmapDrawable and apply it with LinearLayout.setBackgroundDrawable()


Solution 3:

Set an imageview as the background for your linearlayout ie:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView android:id="@+id/myimageview"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"/>
</LinearLayout>

Then, in your Java:

ImageView mImageView = (ImageView)findViewById(R.id.myimageview);

Bitmap bmImg;

URL myFileUrl = put in your url here;          
try {
       myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
     // TODO Auto-generated catch block
       e.printStackTrace();
}
try {
       HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
       conn.setDoInput(true);
       conn.connect();
       InputStream is = conn.getInputStream();

       bmImg = BitmapFactory.decodeStream(is);
       mImageView.setImageBitmap(bmImg);
} catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
}

Hope this helps. Also, see this reference(where I got the image downloading code).


Post a Comment for "LinearLayout Background And Images From Web"