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.

Upvotes: 13

Views: 14622

Answers (6)

AliReza
AliReza

Reputation: 184

You can use :

String name = ((view != null) && (view.getId() != View.NO_ID)) ? getResources().getResourceEntryName(view.getId()) : "";

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

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

Upvotes: 9

Yuri Chervonyi
Yuri Chervonyi

Reputation: 166

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"

Upvotes: 14

Ahmed Khalaf
Ahmed Khalaf

Reputation: 1419

You may do something like this:

    for(Field field : R.id.class.getFields()) {
        try {
            if(field.getInt(null) == R.id.helloTV) {
                Toast.makeText(this, field.getName(), Toast.LENGTH_LONG).show();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

Pros:

  • No need for manually setting the tag. So you may use the tag for other purposes.

Cons:

  • Slower due to reflection.

Upvotes: 2

Ravi
Ravi

Reputation: 35559

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();

Upvotes: 3

rahul
rahul

Reputation: 1105

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

Upvotes: 14

Related Questions