is there any possibility to set background image dynamically?!
I try to explain what I mean.
String picVariable = getPictureFromServer();
ImageView image = (ImageView)v.findViewById(R.id.dynamic_image);
// I know, that doesn't work, but that's the way I looking for
image.setBackgroundResource(picVariable);
Thank you in advance,
Mur
Ps.
I also read this article. It would suggested in one answer, to use java reflection to get a field of the R class by name. But I've never used reflextion before. An example would be very helpfull
Sometimes I should take a bit more time for searching :)
I found the answer reading this article, and it works fine for me:
// The server says, it should be *.png
String picName = getPictureFromServer();
picName = picName.replace(".png", "");
Resources r = getResources();
int picId = r.getIdentifier(picName, "drawable", "com.mypackage.myapp");
ImageView image = (ImageView)v.findViewById(R.id.dynamic_image);
image.setBackgroundResource(picId);
ImageView does not have any background, but for other widget (like Button), you should use setBackgroundResource(int).
Sorry, I am not sure I read the question correctly... maybe your problem is just that you are trying to use it with a Widget that does not use background ?
Related
I'm trying to use android's VectorDrawable as Image source in NativeScript. Using layout inspector I can see that there is something but no image is displayed. Also there is no error about missing image file, no errors at all.
I couldn't find out whether it's possible or not.
Thanks a lot in advance.
So I somehow figured it out:
let context = application.android.context;
// vector is VectorDrawable name
let logo = context.getResources()
.getIdentifier(this.vector, "drawable", context.getPackageName());
this.el.nativeElement.android.setBackgroundResource(logo);
// Access CSS color to change fill color
let backgroundColor: string = (this.el.nativeElement.backgroundColor)
? this.el.nativeElement.backgroundColor.toString()
: SrcDirective.DEFAULT_COLOR;
let newBackgroundColor: Color = new Color(backgroundColor);
this.el.nativeElement.android.getBackground().setTint(newBackgroundColor.android);
I'm using Xamarin Android and I'm trying to change the ImageView src dynamically. All the pictures are placed in Resource/drawable. After reading the picture name as string from an xml (string imgName = nameFromXml + ".jpg") I would like to passing it to my ImageView. I guess there are two good ways:
1) Get the image (int)id and passing it to the ImageView using SetImageResource():
myTextView.SetImageResource(????????);
2) Get the Uri of the of the Image
EDIT
Unfortunately I couldn't use Eric answer for QuinDa question because there are many methods not existing on Xamarin Android, working just in Android.
Here is the standard Android method:
int resImage = getResources().getIdentifier(imgName , "drawable", getPackageName());
myTextView.setImageResource(resImage);
Please note that imgName variable must not contain file extension.
Xamarin.Android C#:
int resImage = Resources.GetIdentifier(imgName, "drawable", PackageName);
Thanks to SushiHangover and Romuald for their answer, but I'd like to share another way that I tested and it looks working well.
Here's how I get the id of the resource:
int resourceId = (int)typeof(Resource.Drawable).GetField("myImageName").GetValue(null);
So, then I'm able to use the normal SetImageResource():
imgViewCondition.SetImageResource(resourceId);
The following code snippet solves the issue:
int id = getResources().getIdentifier("XXX", "drawable", getPackageName());
imageView.setImageResource(id);
Just this:
FindViewById<ImageView>(Resource.Id.imageviewName).SetImageResource(Resource.Drawable.nameofimage);
I know it's an old question, but it never hurt to help.
The image should be stored in all the proper sizes for android inside the Resources Folder
(drawable-hdpi, drawable-ldpi ....)
and then you get it dynamically like so
imageView.SetImageResource(Resource.Drawable.YourImageNameHere);
Ok, after searching and browsing over the internet, I just didn't get what I was looking for. I have a database with a field for "Path", where my images file names are listed.
**Table1:**
PATH ID
imgRice.jpg 1
imgMango.jpg 2
imgBanana.jpg 3
Now I want my imageView to change picture accordingly from my query:
"Select Path from table1 where ID = 1";
I will declare a String, like String queryResultString to handle the result (ex.imgRice.jpg).
I want a code that looks like imgView.image="drawable/" + queryResultString
Any help is appreciated. Thanks guys!
Thanks for the comments and suggestions guys, highly appreciated.
But I've got a simple yet tricky turnaround for my problem.
First, it is IMPOSSIBLE to rip the Drawable path because it is compressed when published to .apk file.
Second, to make it possible, you need to use id for every file in your drawable.
Third, it is much better to add files(images) to asset folder(\app\src\main\assets).
Lastly, follow these simple codes:
//code to initiate the object ImageView...
ImageView myImage = (ImageView) findViewById(R.id.pic);//pic is the id of ImageView in my xml file...
try
{
// now, get the input stream
InputStream input= getAssets().open(c.getString(c.getColumnIndex("image")));//image is the name of field in my db which holds the path (ex. rice.jpg)...
// initiate image as drawable
Drawable draw = Drawable.createFromStream(input, null);
// set image to ImageView
myImage.setImageDrawable(draw);
}
catch(IOException ex)
{
return;
}
Enjoy Coding! ^_^
I've downloaded a webpage html and the images inside it. Now, i'm trying to display them to the user. I've tried two different methods, and not sure which is best to use. Both have their issues.
First, I tried a text view with the following code:
TextView content = (TextView)findViewById(R.id.article_content);
MyImageGetter mig = new MyImageGetter(this, urlId);
Spanned span = Html.fromHtml(contents, mig, null);
content.setText(span);
I really like how this works, except two issues. The first, and most difficult is when an article has lots of images, I get OutOfMemory fc's. MyImageGetter code is as follows
public class MyImageGetter implements Html.ImageGetter{
String urlId = null;
Context c = null;
public MyImageGetter(ArticleViewer articleViewer, String urlId2) {
c = articleViewer;
urlId = urlId2;
}
public Drawable getDrawable(String source) {
String[] brokenUrl = source.split("/");
String imgName = brokenUrl[brokenUrl.length-1];
File image = new File("/data/data/com.that1dev.RibbonReader/Offline/" + urlId + "/" + imgName);
Log.w("MyApp", image.getAbsolutePath());
Bitmap bm = BitmapFactory.decodeFile(image.getAbsolutePath());
Drawable d = new BitmapDrawable(c.getResources(), bm);
d.setBounds(0,0, d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
}
The other issue is the textview has different widths based on user choice and device orientation. The images in the view simply get cropped if they are larger than the textview width. However, I believe I can fix that without too much difficultly on my own. I just haven't tried too hard yet since I'm trying to fix the memory issue first. However, any assistance on either would be much appreciated.
The other method I've tried is a webview.
WebView webContent = (WebView)findViewById(R.id.web_content);
webContent.loadDataWithBaseURL("", contents[1], "text/html", "utf-8", "");
webContent.setBackgroundColor(Color.TRANSPARENT);
Unfortunately with this, the background stays white no matter what I try, and is incredibly ugly. I cannot seem to find a work around that works in 3.0 and 4.0.
If I had a choice, I'd really like the TextView method to work, since I preferred the look of it to the way the WebView rendered things.
What you're trying to do here, fundamentally, is change how the web content is rendered - swapping out what the website writer (which might be you, I don't know) wrote the background to be. Anyway HTML doesn't really support transparent backgrounds of the web content, so the only thing I can think of that you might try is to actually edit the web content via JavaScript:
myWebView.loadUrl("javascript:document.body.style.backgroundImage=\'\');
document.body.style.backgroundColor=\"#00FF00\");");
(Replace the above color with the color of your choice) calling that after the WebView loads will clear any background on the HTML, but you'll still have issues when it comes to any nested styling not on the body.
As for your image problem, you're opening all of the images at their default size and keeping them in memory. One of the things that the WebView does for you is to keep decimated (as in shrunk) renderings of the webpage images. If you want to fix your memory footprint, your best bet is to temporarily save the images to disk, and only open them when the user has scrolled to where the image needs to be - which is not going to be easy, by any means, but that's the only way to ensure that you aren't going to overflow your allocated heap space.
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.
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.
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.
EDIT: added create image from InputStream...
I had the similar problem using ImageButton. I figured it out by loading bitmap from assets and using it as image for ImageButton. Probably not a good approach, but is working and solved my problem - unability to have subfolders in drawable dir and not allowed characters in file names.
(Yes, I can use prefix instead of subdir, and rename files to match the pattern (lowercase only and numbers) and I probably will do it later.)
InputStream is = null;
try {
is = this.getResources().getAssets().open("Images/Fruits/Apple.png");
} catch (IOException e) {
Log.w("EL", e);
}
Bitmap image = BitmapFactory.decodeStream(is);
ImageButton ib2 = (ImageButton) findViewById( R.id.imageButton2);
ib2.setImageBitmap( image);