简体   繁体   中英

Custom xml with references to drawable resources

I have a raw xml resource representing a level file. I want to reference a drawable in this file but I don't have a good idea how to do it - because I don't really know a drawable id. What is a good way to do this?

Assuming you have a drawable resource that has a filename you know, you could use the filename, and get the id like this:

String mDrawableName = "stringFromXML";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

(via How do I get the resource id of an image if I know its name? )

(I see I have a completely different understanding of your question then the other answer: to be clear: I'm assuming you have an XML you made yourself, representing a level in a game. So the XML is your personal thing, not an android layout-xml, and 'level' is also something specific to your application)

Why are you doing it that way, exactly? If you're using a LevelListDrawable, it'll change the drawable automatically when the level changes. That said, if you really need to get the Drawable from it, you might try something like this (eg you need the drawable for level 3):

ImageView iv = (ImageView)findViewById(R.id.imageview);
LevelListDrawable lld = (LevelListDrawable)iv.getDrawable();
int temp = lld.getLevel();
lld.setLevel(3);
Drawable d = lld.getCurrent();
lld.setLevel(temp);

There's probably an easier way to accomplish what you're trying to do though, if you can elaborate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM