Vinc
Vinc

Reputation: 695

Android check if a View has a tag

Is there any way to check if a view has a tag?

I have two views to differentiate from and currently I'm using the tag. I have checked http://developer.android.com/reference/android/view/View.html for all methods involving tags and have not found any way to check if a tag exists.

So currently I'm using :

if(null == v.getTag(R.string.tagid)){
    // do stuff
}

But I try to avoid null checking as far as possible and I'm just wondering if there is a way to check if the view has a tag or if there's a different way to differentiate between two views(I don't have a id to compare to so I can't use the id).

Upvotes: 4

Views: 3213

Answers (2)

Murulimadhav
Murulimadhav

Reputation: 107

Object myObject = tv.getTag();
if (myObject != null) {
}

Upvotes: 0

Antrromet
Antrromet

Reputation: 15414

No, theres no other way. You will have to check for null conditions. The getTag() returns an object which might be null, so yea its best to compare it against null before doing any further manipulation to it.

UPDATE
Instead of using string values as ids, its best to use specific ids that are defined in your ids.xml.

Upvotes: 4

Related Questions