android – 来自AlertDialog的ArrayAdapter notifyDataSetChanged不起作用
作者:互联网
我在Listview中显示我的SQLite数据库中的项目.对于添加项目,我使用AlertDialog.在ALertDialog中,我将项目保存在我的数据库中,并使用数据库中的数据刷新List(userLists).然后我使用notifyDataSetChanged但视图不会改变.
public class MediUserListsFragment extends Fragment {
private MediDAO mediDAO;
private ListView listView;
private List<UserList> userLists;
private ArrayAdapter<UserList> adapter;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Medikamenten Listen");
final View view = inflater.inflate(R.layout.fragment_medi_user_list, container, false);
setHasOptionsMenu(true);
mediDAO = new MediDAO(getContext());
userLists = mediDAO.getAllUserList();
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, userLists);
listView.setAdapter(adapter);
Button newLstBtn = (Button) view.findViewById(R.id.new_list_button);
newLstBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View alertLayout = inflater.inflate(R.layout.dialog_medi_list_new, null);
final EditText newLstName = (EditText) alertLayout.findViewById(R.id.newListName);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setTitle("Neue Liste");
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setPositiveButton("Erstellen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mediDAO.newUserList(newLstName.getText().toString());
userLists = mediDAO.getAllUserList();
adapter.notifyDataSetChanged();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
});
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_medi_abc, menu);
}
}
解决方法:
在setPositiveButton中,尝试以下操作.
userLists.clear();
userLists.addAll(mediDAO.getAllUserList());
adapter.notifyDataSetChanged();
当你做userLists = mediDAO.getAllUserList();适配器丢失原始数据对象的引用(即userLists).使用userLists.addAll(),适配器知道它创建的数据对象已更改,因此notifyDataSetChanged找到要通知的更改.
标签:android,listview,android-arrayadapter,notifydatasetchanged 来源: https://codeday.me/bug/20190608/1199413.html