如何在添加或删除ListView元素时阻止ListView删除数据?

时间:2016-05-07 11:17:32

标签: android listview android-arrayadapter

这是我的代码,我不知道为什么每当我使用CustomAdapter的add或remove方法扩展ArrayAdapter时数据总是被删除。

public class SetFragment extends Fragment {

private CustomAdapter listAdapter = null;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.set_fragment  ,  container  , false);


    List<String> num_set= new ArrayList<>();
    num_set.add("Set1");

    listAdapter = new CustomAdapter(getActivity(), num_set);
    ListView listView = (ListView)view.findViewById(R.id.setListView);
    listView.setAdapter(listAdapter);


    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            listAdapter.remove(listAdapter.getItem(position));
            listAdapter.notifyDataSetChanged();
            return false;
        }
    });
    return view;
}

public void addListData(String entry) {
    int numsets = listAdapter.getCount()+1;
    listAdapter.add(entry+numsets);
}

}

public class CustomAdapter extends ArrayAdapter<String> {

public CustomAdapter(Context context, List<String> num_set ) {
    super(context, R.layout.custom_row_for_set  ,num_set);
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater buclysInflater = LayoutInflater.from(getContext());
    View CustomView = buclysInflater.inflate(R.layout.custom_row_for_set ,parent , false);

    String setNum = getItem(position);
    TextView setText = (TextView)CustomView.findViewById(R.id.setTExtView);

    setText.setText(setNum);
    return CustomView;
}

}

当我点击添加设置按钮时,数据就会消失。我想保留它。 我怎样才能做到这一点?? 你可以看一下附带的照片。

the pic1

pic 2

1 个答案:

答案 0 :(得分:1)

listAdapter.notifyDataSetChanged();方法中添加addListData()