如何处理重复上的自定义组件点击/触摸?
所以,我有具有从0到通过XML包括在同一用户界面组件6的屏幕。类似这样的内容:
So, I have a screen that has from 0 to 6 of the same user interface components included via XML. Something similar to this:
<TableRow android:layout_height="150px">
<include android:id="@+id/p1" android:layout_width="fill_parent"
android:layout_height="wrap_content" layout="@layout/numerics_component"
android:onClick="onClick" />
</TableRow>
<TableRow android:layout_height="150px">
<include android:id="@+id/p2" android:layout_width="fill_parent"
android:layout_height="wrap_content" layout="@layout/numerics_component"
android:layout_below="@id/p1" android:onClick="onClick" />
</TableRow>
...等
每个那些包括UI的是几个小部件,而且我重用自定义组件的集合。
Each of those included UI's is a collection of several widgets and custom components that I am reusing.
我要来检测组件点击在我的活动包括那些位,做出适当的反应。问题是,在我的onClick方法,如果我按照常见的模式,我永远无法知道其中的观点得到了点击:
I want to detect clicks on components in those included bits in my Activity and respond appropriately. The problem is, in my onClick method if I follow the common pattern, I can never tell which of the views got a click:
public void onClick(View view) {
Log.d(loggingName, "Got onClick event on view: " + view);
// Identify the view, and handle appropriately:
switch (view.getId()) {
...
通过上面的code我永远无法知道哪些组件的6份中得到了点击。必须有做到这一点的好办法,但我没有看到它。
With the above code I can never tell which of the 6 copies of the component got clicked. There must be a good way to do this, but I am not seeing it.
此外,我不想硬code中的可重用组件的一个活动,因为我想重新使用它贯穿多个活动,我的应用程序。所以,理想情况下,我可以设置在我的活动听众。
Further, I don't want to hard code the reusable component to one activity because I want to reuse it throughout multiple activities in my app. So ideally, I'd be able to setup the listeners in my Activity.
我如何能做到这一点任何想法?
Any ideas on how I can do this?
谢谢!
1)Android的View类允许你通过的 setTag 方法。
1) The Android View class allows you to tag each instance of a view via the setTag method.
所以,只要 setTag()
与一些独特的整数,甚至也许你会调用对象的方法每个视图。然后在点击监听器,只是做了 getTag()
的各种视图实例之间进行区分。
So, just setTag()
on each view with some unique Integer, or even perhaps an object with a method that you will invoke. Then in your click listener, just do a getTag()
to differentiate between the various view instances.
2)你可以把一个独特的onClickListener每个视图实例。
2) You can put a unique onClickListener on each of the view instances.
3)你可以在每个视图的实例做 findViewById()
,并将它们存储在成员变量,数组或一些其它数据结构。然后在你的 onClickListener
,您只需比较传递给查看引用的onClick()
对你保存的参考书目。
3) You could do a findViewById()
on each of the view instances, and store them in member variables, an array, or some other data structure. Then in your onClickListener
, you simply compare the View reference passed to onClick()
against your list of saved references.