开发者

include tag in xml file of Android Programming

开发者 https://www.devze.com 2023-01-08 21:31 出处:网络
I have a question regarding thetag. Actually I am new to the Android Programming and I want to use the Concept of Reusability in my Application at several 开发者_JS百科places. I get to know that it is

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 开发者_JS百科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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消