AlexanderZC AlexanderZC - 2 months ago 10
Android Question

ListActivity: Add reaction when pressing on List Item

I'm just starting out with java/android studio and wrote the following ListActivity:

public class TransmitChapterSel extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
String[] chapters = {"Chapter 1", "Chapter 2", "Chapter 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, chapters);
getListView().setAdapter(adapter);
}

}


But I don't know how i can produce a reaction when I click/touch/hold one of the list items.

What I want to produce is something like this:

pseudocode:

If(ActionEvent e == Chapter1Pressed){
//do stuff
}


or:

pseudocode:

while(ActionEvent e == Chapter1HeldDown){
//do stuff
}

Ben Ben
Answer

If you only need to know when an item is clicked you can just use an onItemClickListener with your list view.

getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
{
   //Do stuff
}});

If you need to know when it's held down you're going to have to create your own list adapter, and set a touch listener on the row. This is a pretty good tutorial on creating list adapters. http://www.vogella.com/tutorials/AndroidListView/article.html#adapterown

Comments