在Android中重设视图-从一种布局移至另一种 [英] Reparent a view in Android - move from one layout to another

查看:85
本文介绍了在Android中重设视图-从一种布局移至另一种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自iOS,可以在另一个视图下重新创建一个视图.我正在尝试找出Android中的对等物.我想在单击图像时将imageview在视图层次结构中的几个位置上移.像这样:

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:

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/

推荐答案

如果我还记得我以前的iOS经验,那么如果将其添加到另一个视图中,则会自动从该视图的旧父视图中删除该视图(我可能错了;-).

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 ;-).

这是您在android上执行相同操作的方式:

Here's how you would do the same on 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);

这篇关于在Android中重设视图-从一种布局移至另一种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆