Reputation: 12388
So I have a TextView variable declared in the activity such as
TextView t;
The activity implements an OnClickListener so it has the function
public void onClick(View v){
//switch (v.getId()) {
//case:.......
}
I know you can use R.id.itemID in the switch statement to tell some item to do something onClick, however, in my case:
1) I'm using a textswitcher with viewswitcher.viewfactory
2) because of the above, in my main xml layout, i'm using
<TextSwitcher> without a surrounding
<TextView> so the only id I have is the textswitcher
so to do something when I click the text of the textview I did
t.setOnClickListener(this)
However, I don't know what to set the case in the switch statement to, so I just used default, which of course could cause some big problems if I set other views and stuff to the listener.
So is there another way to set the onclicklistner on textview without an xml id or is there a way to figure out the id of the textview?
Thanks!
Upvotes: 0
Views: 905
Reputation: 64700
Well, even if you are using a ViewSwitcher, there is no reason why you can't set an id on the TextView in the XML file.
However, if you insist on not setting an id in xml, then you can do this:
ViewSwitcher vs = (ViewSwitcher)findViewById(R.id.viewswitcherid);
for(int i=0;i<vs.getChildCount();i++){
if(TextView.class.isInstance(vs.getChildAt(i))){
vs.getChildAt(i).setId(R.id.textviewid);
break;
}
}
and you'll have an id you can use in your switch statement.
Upvotes: 0
Reputation: 7350
you could do t.setTag("yourTag") (see http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object) and then do v.getTag in if statements rather than a switch statement since it will be a string.
or alternatively, I think you can define a unique id in your resources (see http://developer.android.com/guide/topics/resources/more-resources.html#Id") then use setTag(int key, tag) http://developer.android.com/reference/android/view/View.html#setTag(int, java.lang.Object)
i've mostly seen people just set a tag and then reference that later.
Upvotes: 1