Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clickable TextView in Android

Tags:

I'm building an Android App that has many many TextViews that I want to be clickable. I've tried to assign the properties android:clickable="true" and android:onClick="clickHandler" to the single TextView and when the app fires the clickHandler(View v) I get the clicked item correctly through v.getId(). What I don't like is to define, for every TextView, the properties android:clickable and android:onClick ... is there something that i can do by code to say: "all the textviews are clickable and click is handled in clickHandler ?"

Thanks.

like image 621
Cris Avatar asked Jan 06 '11 09:01

Cris


People also ask

Can you make a TextView clickable in Android?

In Android, the most common way to show a text is by TextView element. The whole text in the TextView is easy to make clickable implementing the onClick attribute or by setting an onClickListener to the TextView.


1 Answers

You could do something like this below - this way they all have the same handler:

public class sticks extends Activity implements View.OnTouchListener { 
  private TextView tv1; 
  private TextView tv2;
  private TextView tv3;

  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    tv1 = (TextView) findViewById(R.id.tv1); 
    tv2 = (TextView) findViewById(R.id.tv2); 
    tv3 = (TextView) findViewById(R.id.tv3); 

    // bind listeners
    tv1.setOnTouchListener(this); 
    tv2.setOnTouchListener(this); 
    tv3.setOnTouchListener(this); 

  } 

  @Override 
  public boolean onTouch(View v, MotionEvent event) { 
    // check which textview it is and do what you need to do

    // return true if you don't want it handled by any other touch/click events after this
    return true; 
  } 
}
like image 142
xil3 Avatar answered Oct 18 '22 18:10

xil3