Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get view name programmatically in Android

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.

like image 476
Alejandro Martínez Martínez Avatar asked Dec 30 '15 10:12

Alejandro Martínez Martínez


4 Answers

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"

like image 200
Yuri Chervonyi Avatar answered Nov 07 '22 00:11

Yuri Chervonyi


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

like image 10
rahul Avatar answered Nov 07 '22 00:11

rahul


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

like image 7
Ωmega Avatar answered Nov 07 '22 00:11

Ωmega


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();
like image 1
Ravi Avatar answered Nov 07 '22 00:11

Ravi