1

我有一个所有用户安装的应用程序的列表视图,并希望用户能够使用setOnItemLongClickListener将列表视图中的每个项目拖放到另一个活动中。这是我当前的编码:

Drag_and_Drop_App.java (snippet):

// implement event when an item on list view is selected via long-click for drag and drop
mListAppInfo.setOnItemLongClickListener(new OnItemLongClickListener(){

    @Override
    public boolean onItemLongClick(AdapterView parent, View view,
            int pos, long id) {
        // TODO Auto-generated method stub
        // get the list adapter
        AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
        // get selected item on the list
        ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
        // launch the selected application
        Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
        return true;
    }


});
}
} 

如您所见,我只是在用户长按列表中的一个项目时设置它,该项目打开(应用程序启动)。但是,既然我想开始拖动序列,我该怎么做呢?我在这里查看了拖放教程,所以我想更好的问题是:

  1. 我需要为列表视图项目分配一个 ID 吗?

  2. 当用户长按一个项目时,我该如何开始拖动过程​​?

    - 我可以创建一个 Drag Activity 类,然后开始该类的新意图吗?

    - 因为我已经做到了,当该项目被长按时,会发生一些事情(比如分配一个 longclicklistener),我可以只创建这两个类吗?

(由教程提供((上面的链接)))

private final class MyTouchListener implements OnTouchListener {
  public boolean onTouch(View view, MotionEvent motionEvent) {
  if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
    ClipData data = ClipData.newPlainText("", "");
    DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
    view.startDrag(data, shadowBuilder, view, 0);
    view.setVisibility(View.INVISIBLE);
    return true;
  } else {
    return false;
  }
}
}

class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);

@Override
public boolean onDrag(View v, DragEvent event) {
  int action = event.getAction();
  switch (event.getAction()) {
  case DragEvent.ACTION_DRAG_STARTED:
    // do nothing
    break;
  case DragEvent.ACTION_DRAG_ENTERED:
    v.setBackgroundDrawable(enterShape);
    break;
  case DragEvent.ACTION_DRAG_EXITED:
    v.setBackgroundDrawable(normalShape);
    break;
  case DragEvent.ACTION_DROP:
    // Dropped, reassign View to ViewGroup
    View view = (View) event.getLocalState();
    ViewGroup owner = (ViewGroup) view.getParent();
    owner.removeView(view);
    LinearLayout container = (LinearLayout) v;
    container.addView(view);
    view.setVisibility(View.VISIBLE);
    break;
  case DragEvent.ACTION_DRAG_ENDED:
    v.setBackgroundDrawable(normalShape);
  default:
    break;
  }
  return true;
}
}
}  

我在这里收集并显示用户在我的班级中安装的应用程序:

   public static List getInstalledApplication(Context c) {
return c.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
}

我在滑动抽屉中设置了这个列表视图,并希望用户能够将列表项拖放到抽屉外的不同活动中。

我是否以正确的方式思考这个问题?

4

0 回答 0