How to get the Drawable name from imageview in android and get it's String name for comparing

爱⌒轻易说出口 提交于 2019-12-25 10:17:17

问题


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-

  1. at first he wants to get the drawable id from the imageview id. (thw drawable which is showing in the imageview)

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!