How to handle clicks / touches on repeated custom components?
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>
... etc
Each of those included UI's is a collection of several widgets and custom components that I am reusing.
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()) {
...
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.
Furth开发者_运维知识库er, 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?
Thanks!
You could search the hierarchy to figure out which sub-component has been clicked. I see that each row of your table has a unique id. Thus, even though the layout is being repeated with identical ids, the view hierarchy does not have identical ids in any sub-tree.
Thus, to identify which sub-component has been clicked obtain the id of the parent view (which in your case is a row) and see which one of the 6 rows the view belongs to. Does that make sense?
1) The Android View class allows you to tag each instance of a view via the setTag method.
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) You can put a unique onClickListener on each of the view instances.
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.
精彩评论