这是我的代码,我不知道为什么每当我使用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;
}
}
当我点击添加设置按钮时,数据就会消失。我想保留它。 我怎样才能做到这一点?? 你可以看一下附带的照片。
答案 0 :(得分:1)
在listAdapter.notifyDataSetChanged();
方法中添加addListData()
。