0

I have a android library project in which a ImageButton is used. The image file is located in src/assets/img. How to use imageButton.setImageUri() to set the image for this button? The library project will be exported as a jar file which will be used for other project. any idea?

code:

try 
{
    // get input stream
    InputStream ims = mContext.getAssets().open("pause.png");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mPauseButton.setImageDrawable(d);
}
catch(IOException ex) 
{
}

the above code is in the lib project. there is another project called ProjectA. projectA will pass its context to mContext for the lib project.

David
  • 57
  • 4

2 Answers2

0

Try below code.

try 
    {
        // get input stream
        InputStream ims = getAssets().open("<Your file name>.<Extension>");
        // load image as Drawable
        Drawable d = Drawable.createFromStream(ims, null);
        // set image to ImageView
        mImage.setImageDrawable(d);
    }
    catch(IOException ex) 
    {
        return;
    }
Techfist
  • 4,314
  • 6
  • 22
  • 32
  • thank you for your quick response. but I got filenotfound exception. I put play.png under project_root/assets. I can see this file in the exported jar. does getAssets() in your code mean Context.getAssets()? – David Dec 12 '13 at 09:40
  • If you writing this code under a activity then call it directly, otherwise it has to be called via a valid context reference, make sure you change the file name inside .open("") to yours file name. – Techfist Dec 12 '13 at 09:42
  • I am sure the file name is correct. the context might not be correct. I use this jar file in projectA, so there is no image there. how can I use the lib project's context? – David Dec 12 '13 at 09:47
  • after I put the image into projectA/assets, it works. But I need the images under lib project. – David Dec 12 '13 at 09:49
0

You cannot get the assets from a jar file. Try to write a function inside the library project to retrieve the assets image.

Ashwin S Ashok
  • 3,623
  • 2
  • 29
  • 36
  • i don't know what the file path is when the jar is imported in another project – David Dec 12 '13 at 09:55
  • The image is in library project? Then you just write a function to get the assets file in tht library project and then call that function in your main project. – Ashwin S Ashok Dec 12 '13 at 09:59
  • yes, the image is in lib project. do you mean I have a function in lib project such as loadSkin(parentDir), then I call this function in projectA and pass current apk dir to this func? if so, what is the specified path for the image? – David Dec 12 '13 at 10:05
  • Path should be your library project's assets/filename.png. – Ashwin S Ashok Dec 12 '13 at 10:07