Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set Background Image from asset folder in android?

Tags:

android

I am facing problem while setting the backGround Image of LinearLayout from asset folder.

String filePath="file:///android_asset/images/test.png";
    Drawable d = Drawable.createFromPath(filePath);
    frontTextView.setBackgroundDrawable(d);

Can someone help me out.

like image 743
Altaf Avatar asked Feb 02 '11 20:02

Altaf


People also ask

How to set image in Drawable XML Android?

Step 1: In this method first of all in your system find your required images and copy the image as we do normally. Step 2: Then open the Android Studio go to the app > res > drawable > right-click > Paste as shown in the below figure. Step 3: Then a pop-up screen will arise like below.

Where to find image Asset in Android Studio?

In the Project window, select the Android view. Right-click the res folder and select New > Image Asset.

How to add image in XML Android Studio?

xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView. Select the image you want press Ok you can see the image on the Design view.


2 Answers

First you create a Drawable object from the asset file:

Drawable d = Drawable.createFromStream(getAssets().open(path_in_assets), null);

and then set it to some View that only supports Drawables as a background.

like image 154
Gerard Avatar answered Sep 18 '22 08:09

Gerard


As far as I'm aware, you cannot access assets directly like you are trying to. You'll need to use the AssetManager class to get at your data if you want to store it as an asset. Here's a pretty decent blog post explaining a bit about resources and assets, though the official documentation is also a good resource, of course.

I'll also add, though, that things like background images are typically best stored in res/drawable and accessed using the R.drawable.* style (the blog post linked above also discusses this) whenever possible. It's not really clear why you need to do it this way from your provided code sample, though, so I suppose that's ultimately your call.

like image 31
eldarerathis Avatar answered Sep 19 '22 08:09

eldarerathis