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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With