在Android中重新显示视图 - 从一个布局移动到另一个布局

时间:2011-10-08 19:34:24

标签: android

我来自iOS,我可以简单地在另一个视图下重新显示视图。我试图找出Android中的等价物。我想在单击视图层次结构时将图像视图移动到几个点。类似的东西:

public boolean onTouchEvent(MotionEvent event) {

    int action = event.getAction();

    //Tile touchBegan
    if(action == MotionEvent.ACTION_DOWN) {
        RelativeLayout rl = (RelativeLayout)(getParent().getParent());
        rl.addView(this);
    }
}

这是一个简化的例子当然..但只是想弄清楚如何在另一个布局下重新父视图。我发现这个搜索的例子看起来非常复杂..

http://blahti.wordpress.com/2011/02/10/moving-views-part-3/

2 个答案:

答案 0 :(得分:38)

如果我记得我的旧iOS经验,如果你把它添加到另一个(我可能是错的;-),它会自动从它的旧父版中删除视图。

以下是你在android上做同样的事情:

ViewGroup parent = (ViewGroup) yourChildView.getParent();     

if (parent != null) {
    // detach the child from parent or you get an exception if you try
    // to add it to another one
    parent.removeView(yourChildView);
}

// you might have to update the layout parameters on your child
// for example if your child was attached to a RelativeLayout before
// and you add it to a LinearLayout now
// this seems very odd coming from iOS but iOS doesn't support layout
// management, so...
LinearLayout.LayoutParams params = new LinearLayout.LayoutP...
yourChildView.setLayoutParams(params);

yourNewParent.addView(yourChildView);

答案 1 :(得分:8)

((ViewGroup)view.getParent()).removeView(view);
newContainer.addView(view)