Get view name programmatically in Android

I am making a small library to encapsulate adapter functionality, and I need to get the view name programmatically. For instance:

<ImageView android:id="@+id/**ivPerson**" android:layout_width="80dp" android:layout_height="80dp"/> 

Now in the code I have a view (ImageView), and I need to get the name of the view → ivPerson. I can get the identifier using view.getId (), but that is not what I need.

Is it possible?

I tried with this:

 String name = context.getResources().getResourceEntryName(view.getId()); 

But not a job.

+7
source share
5 answers

You can do this by setting the tag as id ie android:tag="ivPerson" and use String name = view.getTag().toString() to get the tag name

+7
source

It is not possible to get ivPerson id using getId() or any other method, however you can get it by setting the tag value as indicated in rahul answer

set tag in xml:

 android:tag="ivPerson" 

choose it in your activity

 view.getTag().toString(); 
+1
source

You can 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 to manually set the tag. This way you can use the tag for other purposes.

Minuses:

  • Slower due to reflection.
+1
source

getResourceName(...) you can use getResourceName(...) .

 String fullName = getResources().getResourceName(view.getId()); 

But there is some problem. This method will give you the full browsing path, for example: "com.google:id/ivPerson"

In any case, you can use this trick to get only the name of the view:

 String fullName = getResources().getResourceName(view.getId()); String name = fullName.substring(fullName.lastIndexOf("/") + 1); 

Now the name will be exactly "ivPerson"

+1
source

For View v we get its name as follows:

 String name = (v.getId() == View.NO_ID) ? "" : v.getResources().getResourceName(v.getId()).split(":id/")[1]; 

If v does not have a name, then name is the empty string "" .

0
source

Source: https://habr.com/ru/post/1239481/


All Articles