在Android中重新父化视图——从一个布局移动到另一个布局

31

我来自iOS,那里我可以简单地将一个视图放置在另一个视图下面。我正在尝试找出Android中的等效方法。当点击时,我想将一个ImageView上移几个位置在视图层次结构中。像这样:

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个回答

47
如果我没记错的话,根据我的旧版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);

谢谢你的帮助,现在这个问题已经解决了!看起来太简单了,我以为我已经尝试过这个方法了。我想我之前将父类强制转换成RelativeLayout布局类型可能导致了问题。 - Daniel

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接