android - How can I get image name? -


i have button , imageview, when click button, there seems 1 of random image in imageview. it's names appear in textview...

        imageview img=(imageview)findviewbyid(r.id.logolar);         random rand = new random();         int rndint = rand.nextint(5) + 1;         string drawablename = "image"+ rndint;         int resid = getresources().getidentifier(drawablename, "drawable", getpackagename());         img.setimageresource(resid);          textview logoismi = (textview)findviewbyid(r.id.logoismi);         logoismi.settext(lastimagename);         clickeddata.add(logoismi.gettext().tostring());          lastimagename = drawablename; 

but code, images names must be; image1 , image2 , image3 ... don't wanna it. images have different names. can different images names code;

    final class drawableclass = r.drawable.class; final field[] fields = drawableclass.getfields();  final random rand = new random(); int rndint = rand.nextint(fields.length); try {     int resid = fields[rndint].getint(drawableclass);     img.setimageresource(resid); } catch (exception e) {     e.printstacktrace(); } 

but can't image name in textview code too. how can solve of it?

use this

getresources().getresourceentryname(int resid); 

or

getresources().getresourcename(int resid); 

your code should

try {     int resid = fields[rndint].getint(drawableclass);     img.setimageresource(resid);     string lastimagename = getresources().getresourceentryname(resid);     //string lastimagename = getresources().getresourcename(resid); // can use     textview logoismi = (textview)findviewbyid(r.id.logoismi);     logoismi.settext(lastimagename); } catch (exception e) {     e.printstacktrace(); } 

update

create array of image id's like

xml file saved @ res/values/arrays.xml

<?xml version="1.0" encoding="utf-8"?> <resources>     <array name="my_array">         <item>@drawable/rose</item>         <item>@drawable/book</item>         <item>@drawable/pen</item>     </array> </resources> 

read this

typedarray ar = context.getresources().obtaintypedarray(r.array.my_array); int len = ar.length(); int[] resids = new int[len]; (int = 0; < len; i++)     resids[i] = ar.getresourceid(i, 0); ar.recycle(); 

use in code this

random rand = new random(); int rndint = rand.nextint(resids.length) + 1; try {     int resid = resids[rndint];     img.setimageresource(resid);     string lastimagename = getresources().getresourceentryname(resid);     //string lastimagename = getresources().getresourcename(resid); // can use     textview logoismi = (textview)findviewbyid(r.id.logoismi);     logoismi.settext(lastimagename); } catch (exception e) {     e.printstacktrace(); } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -