在android中拖动后更改列表顺序

时间:2013-05-31 06:29:39

标签: android android-listview

我在我的列表视图中使用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"};

1 个答案:

答案 0 :(得分:0)

您需要更改(覆盖)DragNDropAdapter的onDrop()方法,以便同步这些更改。