Ali Allahyar
Ali Allahyar

Reputation: 341

How to set external images as background for an app layout

I want to set an image which is in the sdcard as a background for one of my XML layout files. I think I should use File inputStream and outputStream as follows:

public void setBackground()
{
    try
    {
        String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/dir/FILENAME.PNG";
        InputStream ins = new FileInputStream(fileName);

        byte[] buffer = new byte[ins.available()];
        ins.read(buffer);
        ins.close();

        FileOutputStream fos = this.getResources().openRawResource(R.drawable.FILE_TO_BE_WRITTEN);

        fos.write(buffer);
        fos.close();
    }
    catch (IOException io) {}
}

However I'm not sure that will work. I want some advice on it to use this way or could get a better approach to do that. Thanks.

Upvotes: 0

Views: 2946

Answers (3)

Yjay
Yjay

Reputation: 2737

You'll need to...

  1. Use a BitmapFactory to retrieve your Bitmap from a file.

    Bitmap bitmap = BitmapFactory.decodeFile(filePath);

  2. Convert the Bitmap to a BitmapDrawable

    BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);

  3. Set the background of your View using setBackgroundDrawable(Drawable)

    myView.setBackground(bitmapDrawable);

Upvotes: 1

TronicZomB
TronicZomB

Reputation: 8747

If by external image you mean one that you provide, in the res/drawable folder, then you can set it as the background in an XML file using android:background="@drawable/file_name" right within the <Layout> tag:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg">

Upvotes: 0

Prachur
Prachur

Reputation: 1110

this is what you need. Loading a bitmap , resizing it and then putting it into imageview or set background of any view Bitmap

Upvotes: 0

Related Questions