How can a button click method find out which item is selected in a ListView?
- by Ian Bayley
I have a single screen with a bank of buttons below a ListView. Entries on the ListView light up in orange when I scroll so I assume that are selected. When I then press the "Delete" button I want the onClickListener to remove the currently selected entry. But getSelectedItemPosition() always gives me -1. If I can't hope to use the GUI controls in this way, please give me another way of getting the same result.
I have even tried setting the onClickListener of the List View to store the index before the button is pressed (in case pressing the button unselects the entry) but even that is always -1 it seems.
Here's the code (without the modification which didn't work)
package com.bayley;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
*
* @author p0074564
*/
public class September extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final ListView myListView = (ListView) findViewById(R.id.myListView);
Button addButton = (Button) findViewById(R.id.AddButton);
Button deleteButton = (Button) findViewById(R.id.DeleteButton);
final EditText editText = (EditText) findViewById(R.id.myEditText);
final ArrayList<String> todoItems = new ArrayList<String>();
todoItems.add("Monday");
todoItems.add("Tuesday");
todoItems.add("Wednesday");
final ArrayAdapter<String> aa =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, todoItems);
myListView.setAdapter(aa);
addButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
todoItems.add(editText.getText().toString());
aa.notifyDataSetChanged();
}
});
deleteButton.setOnClickListener(new
Button.OnClickListener() {
public void onClick(View v) {
// always returns -1 unfortunately ie nothing is ever selected
int index = myListView.getSelectedItemPosition();
if (index >= 0) {
todoItems.remove(index);
}
aa.notifyDataSetChanged();
}
});
}
}