I would like to delete a clicked item in ListView.
The solution is to use an ArrayList instead of a String[];
Here is my code:
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Critères Supplémentaires");
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
onCancel(dialog);
}
}
);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mView = inflater.inflate(R.layout.fragment_dialog, null);
ListView mListView = (ListView) mView.findViewById(R.id.lvListe);
String[] mValues = {"Orientation", "Nombre de Chambres", "Nombre de Salle de bains", "Nombre de toilettes", "Cave", "Parking", "Garage", "Jardin"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mValues);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) parent.getItemAtPosition(position);
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "You selected : " + item, Toast.LENGTH_SHORT).show();
}
});
builder.setView(mListView);
return builder.create();
}
But adapter.remove() makes the application crash with this error:
java.lang.UnsupportedOperationException
What should I do if I want remove an item ?
Thanks in advance :)
String[] mValues = {"Orientation", "Nombre de Chambres", "Nombre de Salle de bains", "Nombre de toilettes", "Cave", "Parking", "Garage", "Jardin"};
final ArrayList<String> list =new ArrayList<String>(Arrays.asList(mValues));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = list.get(position);
list.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "You selected : " + item, Toast.LENGTH_SHORT).show();
}
});
DO this way
mListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) adapter.getItem(position);
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "You selected : " + item, Toast.LENGTH_SHORT).show();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With