Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include tag in xml file of Android Programming

Tags:

android

xml

I have a question regarding the tag. Actually I am new to the Android Programming and I want to use the Concept of Reusability in my Application at several places. I get to know that it is possible by the tag but I don't know how to use that. I have refered some of it's examples from the net but didn't found them quite satisfactory.

Can anybody please make me understand it with a Clear and appearant example!

Thanks john

like image 947
John Avatar asked Dec 04 '22 12:12

John


1 Answers

Let's say on an activity you have several buttons, all almost doing similar stuff onClick. Now you can use an onClick method, but since you cannot pass parameters in the onClick attribute, you need to put it somewhere else, which is where tag comes in handy.

In your layout you might have:

<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 custom onClickListener (especially if you want to reuse amonst multiple activities) or like in my case just a method in my activity for your buttons that handle the actions for it.

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

This is especially useful for generic actions, and also if you want to reuse code (i.e. same button listener) amongst multiple classes/activities. This way you don't rely on a switch/case and checking your button (view) id; staying more independent from your activity itself.

like image 55
Mathias Conradt Avatar answered Dec 17 '22 06:12

Mathias Conradt