I followed this google tutorial and implemented a dynamic ListView for drag and drop https://www.youtube.com/watch?v=_BZIvjMgH-Q
listView = (DynamicListView) findViewById(R.id.listview);
adapter = new StableArrayAdapter(this, R.layout.text_view, arraylist);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// added the items later and called notifyDataSetChanged();
arraylist.add("item 1");
arraylist.add("item 2");
arraylist.add("item 3");
arraylist.add("item 4");
adapter.notifyDataSetChanged();
It shows up all the items in the listview but when I drag and drop the elements they disappear.
If I add the elements before setting the adapter listView.setAdapter(adapter);
it works totally fine.
Library Source code http://developer.android.com/shareables/devbytes/ListViewDraggingAnimation.zip
How do i fix this?
UPDATE
StableArrayAdapter.java
package com.example.android.navigationdrawerexample;
import android.content.Context;
import android.widget.ArrayAdapter;
import java.util.HashMap;
import java.util.List;
public class StableArrayAdapter extends ArrayAdapter<String> {
final int INVALID_ID = -1;
int mRowLayout;
List<String[]> mStrings;
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
// constructor
public StableArrayAdapter(Context context, int rowLayout, List<String> objects) {
super(context, rowLayout, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
if (position < 0 || position >= mIdMap.size()) {
return INVALID_ID;
}
String item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
UPDATE 2 I added the items to objects here as suggested and it works fine for now but isn't it the same as adding the items in MainActivity before setting the adapter?
public StableArrayAdapter(Context context, int rowLayout, List<String> objects) {
super(context, rowLayout, objects);
objects.add("item 1");
objects.add("item 2");
objects.add("item 3");
objects.add("item 4");
objects.add("item 5");
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
UPDATE 3 The size of the objects is known only in the constructor and mIdMap.put("item 6", objects.size()); in the code has no effect.
// constructor
public StableArrayAdapter(Context context, int rowLayout, List<String> objects) {
super(context, rowLayout, objects);
this.objects = objects;
objects.add("item 1");
objects.add("item 2");
objects.add("item 3");
objects.add("item 4");
objects.add("item 5");
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
mIdMap.put("item 6", objects.size()); // has no effect
}
public void addItem(String item) {
int index = objects.size();
mIdMap.put(item, index);
}