How to get id attribute of xml android view element in java code

Suppose I have an xml definition for a button with id like @+id/send_button

How can I get this id attribute value in Java code? I tried the getXXX methods in the AttributeSet class, but does not provide any value that send_button has.

Edit1:

Let me make this a little clearer.

I am creating a custom component View , and I want to know that the id value that the user of this component provided in the XML file.

Edit2:

I do not use custom attributes for a specific reason, but using

 <mycomponent android:id="@+id/my_id"/> 

Edit 3:

AttributeSet has a getIdAttribute() method, but it just doesn't work. Does anyone know the reason?

+4
source share
2 answers

As I understand it, you are creating a custom view, and after you get this view, you want to get the identifier of this view. Why and how you do this is still not very clear to me.

But if your custom view is a subclass of View, there must be a getId () method that will return the identifier assigned to this view.

+3
source

I still do not understand what exactly you are asking, but the getTag View method will retrieve the string set in the XML element via "android: tag".

So ... essentially, this is the same effect if you don't mind that an additional attribute is added to your XML.

 <mycomponent android:id="@+id/my_id" android:tag="my_id" /> 

and then in your code ...

 String nodeId = myComponentInstance.getTag(); 
+2
source

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


All Articles