Android: How to convert 'view' to 'textview'?

Dave picture Dave · Nov 22, 2011 · Viewed 12.4k times · Source

I have a number of TextViews that each share a single OnLongClickListener

Within the onLongClick event, I want to identify which TextView triggered the event.

However, the event is defined as:

public boolean onLongClick(View view) 

I tried casting view to TextView, but that didn't work.

How can I get at the widget that triggered the OnLongClick event?

Answer

kaspermoerch picture kaspermoerch · Nov 22, 2011

The View should be your TextView.

Try something like this:

if( view instanceof TextView ) {
  TextView textView = (TextView) view;
  //Do your stuff
}

To verify that the above if-statement is valid you can try running it like this first:

if( view instanceof TextView ) {
  Log.e( "MyTag", "It's a TextView!" );
}