У меня есть ELV с некоторыми дочерними элементами, основанными на String ArrayList, который отображается во фрагменте. Для каждого дочернего элемента есть кнопка удаления, чтобы пользователь мог удалить конкретный элемент. Элемент будет успешно удален из ArrayList, но он не будет обновляться в пользовательском интерфейсе. Я должен перейти на другую страницу и вернуться на нее, чтобы она была показана , что она удалена. Я просмотрел некоторые посты, в которых упоминаются методы notifyDataSetChanged () или notifyDataSetInvalidated () для адаптера, но он все еще не обновляет список в пользовательском интерфейсе. Я пытался использовать методы в моем фрагменте, и это тоже не работает. Я не помещаю это в правильное место или я пропускаю что-то еще?
Метод getChildView в пользовательском классе ExpandableListAdapter.java:
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
int buttonToHide = SessionsActivity.whichInflate;
if(convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item, null);
}
// TextView which will hold the text of the child item
TextView textListChild = convertView.findViewById(R.id.listItem);
// Button to add a session (for SessionsFragment.java)
ImageButton addButton = convertView.findViewById(R.id.addButton);
// Button to delete user choice session (for YourSessionsFragment.java)
ImageButton deleteButton = convertView.findViewById(R.id.deleteButton);
final View finalConvertView = convertView;
// if the int value in SessionsActivity.java is 0 -> hide the delete button, 1 -> hide the add button
if(buttonToHide == 0) {
deleteButton.setVisibility(View.GONE);
}
else if(buttonToHide == 1) {
addButton.setVisibility(View.GONE);
}
// Listener for the add button
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Check group position to add child to right group
if(groupPosition == 0) {
// Check to add session if it already hasn't beed added
if(!sessionExists(childText, YourSessionsFragment.userSessions22)) {
Toast.makeText(finalConvertView.getContext().getApplicationContext(), childText + " added to your sessions", Toast.LENGTH_SHORT).show();
// Add the session to the ArrayList
YourSessionsFragment.userSessions22.add(childText);
}
else {
Toast.makeText(finalConvertView.getContext().getApplicationContext(),"This session has already been added", Toast.LENGTH_SHORT).show();
}
}
else {
if(!sessionExists(childText, YourSessionsFragment.userSessions23)) {
Toast.makeText(finalConvertView.getContext().getApplicationContext(), childText + " added to your sessions", Toast.LENGTH_SHORT).show();
YourSessionsFragment.userSessions23.add(childText);
}
else {
Toast.makeText(finalConvertView.getContext().getApplicationContext(),"This session has already been added", Toast.LENGTH_SHORT).show();
}
}
}
});
// Listener for delete button
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Check group position to delete the right child item
if(groupPosition == 0) {
// Check if the session exists
if(sessionExists(childText, YourSessionsFragment.userSessions22)) {
Toast.makeText(finalConvertView.getContext().getApplicationContext(), childText + " removed from your sessions", Toast.LENGTH_SHORT).show();
// Remove it from the ArrayList
YourSessionsFragment.userSessions22.remove(childPosition); // Remove item from arrl
YourSessionsFragment.listDataChild.remove(childText); // Remove item from YourSessionsFragment class
_listDataChild.remove(childText); // Remove item from this class
YourSessionsFragment.expandableListAdapter.notifyDataSetChanged(); // Why doesn't this work???
YourSessionsFragment.expandableListView.setAdapter(YourSessionsFragment.expandableListAdapter);
}
else {
Toast.makeText(finalConvertView.getContext().getApplicationContext(),"This session has already been removed", Toast.LENGTH_SHORT).show();
}
}
else {
if(sessionExists(childText, YourSessionsFragment.userSessions23)) {
Toast.makeText(finalConvertView.getContext().getApplicationContext(), childText + " removed from your sessions", Toast.LENGTH_SHORT).show();
YourSessionsFragment.userSessions23.remove(childPosition); // Remove item from arrl
YourSessionsFragment.listDataChild.remove(childText); // Remove item from YourSessionsFragment class
_listDataChild.remove(childText); // Remove item from this class
YourSessionsFragment.expandableListAdapter.notifyDataSetChanged(); // Why doesn't this work???
YourSessionsFragment.expandableListView.setAdapter(YourSessionsFragment.expandableListAdapter);
}
else {
Toast.makeText(finalConvertView.getContext().getApplicationContext(),"This session has already been removed", Toast.LENGTH_SHORT).show();
}
}
}
});
// Set the text of the child item
textListChild.setText(childText);
return convertView;
}
YourSessionsFragment.java (здесь отображается ELV)
public class YourSessionsFragment extends Fragment {
public static ArrayList<String> userSessions22 = new ArrayList<>();
public static ArrayList<String> userSessions23 = new ArrayList<>();
public static ExpandableListAdapter expandableListAdapter;
ExpandableListView expandableListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sessions, container, false);
// Get the ListView
expandableListView = view.findViewById(R.id.sessionsExpandableListView);
// Prepare the list data
prepareListData();
expandableListAdapter = new ExpandableListAdapter(getContext(), listDataHeader, listDataChild);
// Set the list adapter and expand lists by default
expandableListView.setAdapter(expandableListAdapter);
expandableListView.expandGroup(0);
return view;
}
/**
* Prepare the list data
*/
public void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
// Header data
listDataHeader.add("22nd May 2018");
listDataHeader.add("23rd May 2018");
// Child data
List<String> may22 = new ArrayList<>();
for(int i = 0; i < userSessions22.size(); i++) {
may22.add(userSessions22.get(i));
}
List<String> may23 = new ArrayList<>();
for(int i = 0; i < userSessions23.size(); i++) {
may23.add(userSessions23.get(i));
}
// Header, Child data
listDataChild.put(listDataHeader.get(0), may22);
listDataChild.put(listDataHeader.get(1), may23);
}
}