问题描述:

I'm rather new to the Android SDK, and I recently started developping a small application. The application centers around a menu, which is implemented using a custom ListView. I used this guide as a reference in order to build my model classes and my adapter. The author also published the code he used on GitHub, here. My result is rather close from the original one, the screen below is from the author's blog post:

I successfully set up my menu, and now comes the time when I need to connect every item of the list to the listener so that I can handle clicks. In order to keep it simple, I had my activity implement OnClickListener:

public class MenuActivity extends ListActivity implements View.OnClickListener

{

@Override

public void onClick(View v) {

// ...

}

}

I was also able to connect my menu items to this method through my menu items' XML files:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:onClick="onClick"

android:id="@+id/menu_item_layout">

Now, whenver I click on one of my list items, I enter the onClick method. However, once I'm there, I can't find a way to distinguish an item from other. As you can see, I applied my click event to their layouts, so that it is triggered when I click an item in it (my texts).

However, since all my items share the same XML layout, they also seem to share the same ID: @id/menu_item_layout. Because of that, I can't do the usual...

public void onClick(View v) {

switch(v.getId()){

case R.id.myId: /* ... */ break;

case R.id.myId2: /* ... */ break;

// ...

}

}

Given this "custom list" implementation, is there a way I could distinguish a click on Menu item1 from a click on Menu item 2?

网友答案:

An OnClickListener will not function as you expect with a ListView. However, the ListActivity class provides the onListItemClick() method, that is implemented as follows:

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{

}

The position parameter will hold the index in the underlying data list corresponding to the item clicked.

网友答案:

When you create a View for a list item in your ListAdapter you can set tag on that view using View#setTag. Put there something which can distinguish one list item from another i.e. position in adapter. Then use View.getTag to get this unique identifier in onClick listener.

网友答案:

What i think is, there are two ways to do this:

First:

Add clicklistener to the view inside the getview method, that way you would also be having the position(remember to initialize a final int to the position inside getView and use that int inside your clickListener)

Second:(not guaranteed if it will work)

Add a tag to every textView inside getView and store the position in that textView. ex:

textView.setTag(new Integer(int position));

and then fetch that position in the onClick method of yours

相关阅读:
Top