Reputation: 341
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
Reputation: 2737
You'll need to...
Use a BitmapFactory
to retrieve your Bitmap
from a file.
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Convert the Bitmap
to a BitmapDrawable
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
Set the background of your View
using setBackgroundDrawable(Drawable)
myView.setBackground(bitmapDrawable);
Upvotes: 1
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