问题
I have two drawable apple and a how to get the drawable name in my code and compare that they starts with same alphabet
Community edited question
Questioner is actually seeking for 2 problems-
at first he wants to get the drawable id from the imageview id. (thw drawable which is showing in the imageview)
then he wants to get the drawable name from that obtained drawable id in step-1.
回答1:
Updated answer
For step-1
There is no direct way. You need to save the drawable id in the imageview's Tag
via setTag()
. then you can retrieve by getTag()
of the imageview.
Step-2
you should get the image name by
String imageName1 = context.getResources().getResourceEntryName(R.drawable.apple);
// now imageName1 should contain "apple".
String imageName2 = context.getResources().getResourceEntryName(R.drawable.a);
// now imageName2 should contain "a".
if(imageName1.toLowerCase().charAt(0) == imageName2.toLowerCase().charAt(0))
{
// starting character 'a' is matching
}
回答2:
Have you tried this?
String name1 = getResources().getResourceEntryName(R.drawable.drawable_id_1);
String name2 = getResources().getResourceEntryName(R.drawable.drawable_id_2);
if (name1.startsWith("a") && name2.startsWith("a")) {
// do something
}
回答3:
Get the full resource name via getResources().getResourceName(R.drawable.XXXX)
. This will return you a string in the form package:type/entry
.
For example my project has the package com.test.app
and a drawable called apple.png
in my resources. Calling the method I mentioned the result will be:
com.test.app:drawable/apple
As you want to compare images in the same project, you can easily truncate the part until the actual name, as it'll be the same for all your images.
来源:https://stackoverflow.com/questions/29488340/how-to-get-the-drawable-name-from-imageview-in-android-and-get-its-string-name