Search code examples
androidlistviewnotifydatasetchanged

Android Listview refreshing - notifyDataSetChanged() option not available


I have a fragment with tablayout (2 tabs inside) and a listview that is populated by String items from .xml file. I want to change the .xml resource file when i click on a tab, but listview doesnt change. I found a lot of answers all saying that I should use notifyDataSetChanged() but I don have that as an option when I type adapter. (no autocomplete option)

This is my code

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class IMFragment extends Fragment {

    private TabLayout tl;
    private String[] sM;
    private String s="x1";

    public IMFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment_im, container, false);

        tl = v.findViewById(R.id.tlID);
        tl.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                s=tab.getText().toString();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        switch (s) {
            case "x1":
                sM = getResources().getStringArray(R.array.x1);
                break;
            case "x2":
                sM = getResources().getStringArray(R.array.x2);
                break;           
        }

        ListView iMLV = v.findViewById(R.id.im_lvID);
        ListAdapter mListAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, sM);

        iMLV.setAdapter(mListAdapter);

        return v;
    }
}

Solution

  • You don't need notifyDataSetChanged if you update your current ArrayAdapter

    public void onTabSelected(TabLayout.Tab tab) {
        s=tab.getText().toString();
    
        ArrayAdapter adapter = (ArrayAdapter) iMLV.getAdapter()
        adapter.clear();
        adapter.addAll(Arrays.asList(getResources().getStringArray(R.array.x2))) // adapt code here to inject right array list
    }