Android中的可点击TextView [英] Clickable TextView in Android
问题描述
我正在构建一个 Android 应用程序,其中包含许多我希望可点击的 TextView.我试图将属性 android:clickable="true"
和 android:onClick="clickHandler"
分配给单个 TextView
以及何时应用程序触发 clickHandler(View v)
我通过 v.getId()
正确获取点击的项目.我不喜欢为每个 TextView
定义属性 android:clickable
和 android:onClick
... 有什么我可以通过代码说:所有文本视图都是可点击的,点击是在 clickHandler
中处理的?"
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
?"
谢谢.
推荐答案
你可以在下面做这样的事情 - 这样他们都有相同的处理程序:
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;
}
}
这篇关于Android中的可点击TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!