我创建了自己的对话框类。该类有一个按钮,用于从列表视图中删除项目(这是主要的acctivity_main.xml)。当我按下删除按钮时,项目不会被删除。
我已经看过这个话题Android: how to remove an item from a listView and arrayAdapter。只是看起来用户不知道如何正确获取项目索引,我相信我已经正确完成了。
Remove ListView items in Android这个非常接近。但是在我的代码中我创建了自己的对话框,这个对话框正在使用正面和负面按钮。我在对话框类和mainActivity之间传递变量。
OnCreate中的onClickListener与MainActivity
mFoodDataAdapter = new FoodDataAdapter();
final ListView listFoodData = (ListView) findViewById(R.id.listView);
listFoodData.setAdapter(mFoodDataAdapter);
//Handle clicks on the ListView
listFoodData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
FoodData tempFoodData = mFoodDataAdapter.getItem(whichItem);
//create a new dialog window
DialogShowFood dialog = new DialogShowFood();
// send in a reference to the note to be shown
dialog.sendFoodDataSelected(tempFoodData);
FoodDataAdapter adapter1 = new FoodDataAdapter();
/*this is where i send the data to the DialogShowFood.java*/
dialog.sendFoodDataAdapter(adapter1, whichItem);
// show the dialog window with the note in it
dialog.show(getFragmentManager(),"");
}
});
这是我的对话框“DialogShowFood.java”
public class DialogShowFood extends DialogFragment {
FoodData mFood;
MainActivity.FoodDataAdapter mAdapter;
int mitemToDelete;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_food, null);
Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete);
builder.setView(dialogView).setMessage("Your food");
/*this sends the item to delete to the adapter*/
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAdapter.deleteFoodData(mitemToDelete);
dismiss();
}
});
return builder.create();
}
/*this gets the data to delete from the MainActivity*/
public void sendFoodDataAdapter(MainActivity.FoodDataAdapter adapter1, int whichItem) {
mAdapter = adapter1;
mitemToDelete = whichItem;
}
}
适配器内的功能
/*this is the function in the base adapter to delete the item*/
public void deleteFoodData(int n){
Toast.makeText(MainActivity.this,Integer.toString(n), Toast.LENGTH_SHORT).show();
foodDataList.remove(n);
notifyDataSetChanged();
}
Toast输出要删除的项目的正确索引,它不会因某种原因删除该项目。