I am doing a small library to encapsulate adapters functionality and I need get the name of a view programmatically. For example:
<ImageView
android:id="@+id/**ivPerson**"
android:layout_width="80dp"
android:layout_height="80dp"/>
Now, in the code I have the view (ImageView) and I need obtain the name of the view --> ivPerson. I can obtain the id with view.getId() but that's not what I need.
It is possible?
I tried with this:
String name = context.getResources().getResourceEntryName(view.getId());
But not work.
You can use getResourceName(...)
instead.
String fullName = getResources().getResourceName(view.getId());
But there is a some problem. This method will give you a full path of view like: "com.google:id/ivPerson"
Anyway, you can use this trick to get only name of a view:
String fullName = getResources().getResourceName(view.getId());
String name = fullName.substring(fullName.lastIndexOf("/") + 1);
Now name
will be exactly "ivPerson"
You can do it by setting tag as the id i.e android:tag="ivPerson"
and use String name = view.getTag().toString()
to get the name of the tag
For the View v
get its name as follows:
String name = (v.getId() == View.NO_ID) ? "" :
v.getResources().getResourceName(v.getId()).split(":id/")[1];
If the view v
has no name, then the name
is an empty string ""
.
There is no way to get ivPerson
id using getId()
or any other method, however you can get it by setting tag value as mentioned in rahul's answer
set tag in xml :
android:tag="ivPerson"
fetch it in your activity
view.getTag().toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With