我对 Android 开发还很陌生,并且仍在学习一些技能,但是遇到了 ListView 和 ArrayAdapter 删除项目的问题。我一直在尝试大量的示例并尽可能多地阅读材料,但我想我可能会遗漏一些东西。对于我的一生,我无法让它在我的代码中工作。
任何帮助,将不胜感激。我在这里包含了代码。
public class Favourites extends ListActivity implements OnClickListener {
private static final String TAG = "favourites";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favourites);
// Test list of strings- eventually to be replaced
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// First paramenter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
setListAdapter(adapter);
ListView list = getListView();
Log.d(TAG,"adapter count: " + adapter.getCount());
// Define listView Long Click listener
list.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
// Remove Item
AlertDialog.Builder adb = new AlertDialog.Builder(Favourites.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to remove " + item +" (" + position + ")");
final int positionToRemove = position;
final String removeItem = item;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// *** Here is where I am experiencing issues ***
adapter.remove(positionToRemove);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Favourite "+ removeItem +" (" + positionToRemove + ") Removed!", Toast.LENGTH_LONG).show();
}
});
adb.show();
// Return true to consume the click event. In this case the
// onListItemClick listener is not called anymore.
return true;
}
});
// Close button
View butClose = findViewById(R.id.closeButton);
butClose.setOnClickListener(this);
// Add button
View butAdd = findViewById(R.id.addButton);
butAdd.setOnClickListener(this);
}