Android Listview刷新 - notifyDataSetChanged()选项不可用

时间:2018-04-03 20:08:14

标签: android listview notifydatasetchanged

我有一个带有tablayout的片段(里面有2个标签)和一个listview,它由.xml文件中的String项填充。我想在单击选项卡时更改.xml资源文件,但listview不会更改。我发现很多答案都说我应该使用notifyDataSetChanged()但是当我输入适配器时我没有这个选项。 (没有自动填充选项)

这是我的代码

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;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您更新当前的notifyDataSetChanged

,则不需要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
}