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

时间:2022-11-15 18:31:57

I'm coming from iOS where I can simply reparent a view under another view. I'm trying to figure out the equiv in Android. I want to move an imageview up a couple of spots in the view hierarchy when clicked. Something like:

我来自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);
    }
}

This is a simplified example of course.. but just trying to figure out how to re-parent a view under another layout. I found this example searching around which seems incredibly complicated..

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

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

2 个解决方案

#1


35  

If I remember my old iOS experience right it removes the view from it's old parent automatically if you add it to another one (I might be wrong ;-).

如果我记得我的旧iOS体验,如果你将它添加到另一个(我可能是错的;-),它会自动从它的旧父节点中删除它。

Here's how you would do the same on android:

这是你在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);

#2


7  

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

#1


35  

If I remember my old iOS experience right it removes the view from it's old parent automatically if you add it to another one (I might be wrong ;-).

如果我记得我的旧iOS体验,如果你将它添加到另一个(我可能是错的;-),它会自动从它的旧父节点中删除它。

Here's how you would do the same on android:

这是你在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);

#2


7  

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