listview.setAdapter(null)似乎不起作用

时间:2018-09-13 10:48:36

标签: java android listview android-adapter

我有一个选项卡布局包含一个列表视图,该列表视图在每次选择一个选项卡时都会更新 但是新项目将添加到列表中,并且在添加新项目之前不会清除列表

public class DemoObjectFragment extends Fragment {
ListView lv;
private String TAG = DemoObjectFragment.class.getSimpleName();
public static ArrayList<HashMap<String, String>> contList = new ArrayList<>();
android.widget.ListAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View vw = inflater.inflate(R.layout.coin, container, false);
    try {
        for (int i = 0; i < contactList.size(); i++) {
            Log.v(TAG, "Response: " + contactList.get(i));
            if (Integer.valueOf(contactList.get(i).get("asset_id")) == MainActivity.typeCurrency) {
                contList.add(contactList.get(i));
            }
        }
    }catch (Exception e){
        e.getMessage();
    }


    lv=vw.findViewById(R.id.exchangeList);
    lv.setAdapter(null);
    adapter = new SimpleAdapter(getActivity(), contList, R.layout.list_item, new String[]{"sourceName", "priceCurrency"},
            new int[]{R.id.sourceName, R.id.priceCurrency});
    lv.setAdapter(adapter);
    contactList=new ArrayList<>();
    return vw;
}

}

2 个答案:

答案 0 :(得分:1)

您需要清除项目,然后将新项目添加到列表中,

 contList.clear();

尝试添加clear()方法。

 try {
    contList.clear();
    for (int i = 0; i < contactList.size(); i++) {
        Log.v(TAG, "Response: " + contactList.get(i));
        if (Integer.valueOf(contactList.get(i).get("asset_id")) == MainActivity.typeCurrency) {
            contList.add(contactList.get(i));
        }
    }
}catch (Exception e){
    e.getMessage();
}

答案 1 :(得分:1)

public class DemoObjectFragment extends Fragment {
ListView lv;
private String TAG = DemoObjectFragment.class.getSimpleName();
public static ArrayList<HashMap<String, String>> contList;
android.widget.ListAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater,
                     ViewGroup container, Bundle savedInstanceState) {
View vw = inflater.inflate(R.layout.coin, container, false);
try {
    contList = new ArrayList<>();
    for (int i = 0; i < contactList.size(); i++) {
        Log.v(TAG, "Response: " + contactList.get(i));
        if (Integer.valueOf(contactList.get(i).get("asset_id")) == MainActivity.typeCurrency) {
            contList.add(contactList.get(i));
        }
    }
}catch (Exception e){
    e.getMessage();
}


lv=vw.findViewById(R.id.exchangeList);
lv.setAdapter(null);
adapter = new SimpleAdapter(getActivity(), contList, R.layout.list_item, new String[]{"sourceName", "priceCurrency"},
        new int[]{R.id.sourceName, R.id.priceCurrency});
lv.setAdapter(adapter);
contactList=new ArrayList<>();
return vw;
   }
}

那会很好;)