如何在android中拖放后将按钮保持在先前的位置

时间:2013-03-06 06:41:16

标签: android button drag-and-drop android-linearlayout android-gridlayout

在我的Android应用程序中,我有一个gridlayout,其中有五个linearlayout。四个linearlayout每个包含一个按钮,另一个linearlayout为空。我想将一个按钮放到空的linearlayout上,当linearlayout不为空时,在放下之后它将采用其先前的线性布局位置。使用此代码

 ViewGroup owner = (ViewGroup) view.getParent();    
 LinearLayout pastContainer = (LinearLayout) owner;

如果目标linearlayout不为空(有孩子),我会得到我想要保留按钮的线性布局。我得到目标linearlayout的孩子,使用此代码检查它是否为空

LinearLayout newcontainer = (LinearLayout) v;
int count = newcontainer.getChildCount();

我可以将一个按钮拖放到空的linearlayout但是当我尝试将一个按钮拖放到带子的线性布局时,它会给出错误。这是我的代码

private class MyDragListener implements OnDragListener 
{
    @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:
            break;
          case DragEvent.ACTION_DRAG_EXITED:
            break;
          case DragEvent.ACTION_DROP:

            View view = (View) event.getLocalState();
            ViewGroup owner = (ViewGroup) view.getParent(); 
            LinearLayout pastContainer = (LinearLayout) owner;
            LinearLayout newcontainer = (LinearLayout) v;
            int count = newcontainer.getChildCount();                           

            if(count==0)
            {
                owner.removeView(view);     
                newcontainer.addView(view);
                view.setVisibility(View.VISIBLE);
            }
            else
            {
                pastContainer.addView(view);
                view.setVisibility(View.VISIBLE);
            }

            break;
          case DragEvent.ACTION_DRAG_ENDED:
          default:
            break;
          }
          return true;
    }             
}

如果目标linearlayout不为空(有孩子),我如何将按钮保持在上一个linearlayout?感谢

0 个答案:

没有答案