Include tag in xml file of Android programming

I have a question regarding a tag. I'm actually new to Android programming, and I want to use the concept of reuse in my application in several places. I find out that this is possible by tag, but I do not know how to use it. I referred to some of these examples from the net, but did not find them quite satisfactory.

Can someone please make me understand this with a clear and explicit example!

Thanks, John

+4
source share
1 answer

Suppose you have several buttons, almost all do similar things onClick. Now you can use the onClick method, but since you cannot pass parameters in the onClick attribute, you need to put it in another place where the tag is useful to you.

In your layout you can:

<Button android:id="@+id/btn1" android:tag="paramValue1" android:onClick="myOnClick"/> <Button android:id="@+id/btn2" android:tag="paramValue2" android:onClick="myOnClick"/> 

Then you can use one central user-defined onClickListener (especially if you want to reuse multiple actions with multiple objects) or, as in my case, only a method in my activity for your buttons that handle actions for it.

 public void myOnClick(View v) { String param = (String) v.getTag(); .... } 

This is especially useful for general actions, and also if you want to reuse the code (i.e. the same button listener) among several classes / actions. Thus, you do not rely on the switch / case and check your button identifier (view); staying more independent of your activities.

+17
source

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


All Articles