我在列表视图中使用 Drag n Drop。它工作得很好,但问题是我如何在拖动后更改元素的顺序。假设我有一个列表视图,其中元素 1 在 0 位置,2 在 1 位置 3 在 2位置等等。因此,当我单击位置 2 处的项目时,它在位置 1 处给了我项目,它也是正确的,但是在拖动后假设我将 2 替换为 1.它应该给我与 1 相关联的数据,但它又给了我数据2.so怎么可能。任何帮助将不胜感激。
这是我的代码:
public class DragNDropListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dragndroplistview);
Button mbtn=(Button)findViewById(R.id.button12);
mbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(DragNDropListActivity.this,FormulaActivity.class);
startActivity(i);
finish();
}
});
ArrayList<String> content = new ArrayList<String>(mListContent.length);
for (int i=0; i < mListContent.length; i++) {
content.add(mListContent[i]);
}
setListAdapter(new DragNDropAdapter(this, new int[]{R.layout.dragitem}, new int[]
{R.id.TextView01}, content));//new DragNDropAdapter(this,content)
ListView listView = getListView();
if (listView instanceof DragNDropListView) {
((DragNDropListView) listView).setDropListener(mDropListener);
((DragNDropListView) listView).setRemoveListener(mRemoveListener);
((DragNDropListView) listView).setDragListener(mDragListener);
}
}
private DropListener mDropListener =
new DropListener() {
public void onDrop(int from, int to) {
ListAdapter adapter = getListAdapter();
if (adapter instanceof DragNDropAdapter) {
((DragNDropAdapter)adapter).onDrop(from, to);
getListView().invalidateViews();
}
}
};
private RemoveListener mRemoveListener =
new RemoveListener() {
public void onRemove(int which) {
ListAdapter adapter = getListAdapter();
if (adapter instanceof DragNDropAdapter) {
((DragNDropAdapter)adapter).onRemove(which);
getListView().invalidateViews();
}
}
};
private DragListener mDragListener =
new DragListener() {
int backgroundColor = 0xe0103000;
public void onDrag(int x, int y, ListView listView) {
// TODO Auto-generated method stub
}
public void onStartDrag(View itemView) {
itemView.setVisibility(View.INVISIBLE);
itemView.setBackgroundColor(backgroundColor);
ImageView iv = (ImageView)itemView.findViewById(R.id.ImageView01);
if (iv != null) iv.setVisibility(View.VISIBLE);
}
public void onStopDrag(View itemView) {
itemView.setVisibility(View.VISIBLE);
itemView.setBackgroundColor(backgroundColor);
ImageView iv = (ImageView)itemView.findViewById(R.id.ImageView01);
if (iv != null) iv.setVisibility(View.VISIBLE);
}
};
private static String[] mListContent={"1","2","3"};