【问题标题】:Reparent a view in Android - move from one layout to another在 Android 中重新设置视图 - 从一种布局移动到另一种布局
【发布时间】:2011-10-08 19:34:23
【问题描述】:

我来自 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/

【问题讨论】:

    标签: android


    【解决方案1】:

    如果我记得我的旧 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 布局类型。也许这导致了我的问题。
    【解决方案2】:
    ((ViewGroup)view.getParent()).removeView(view);
    newContainer.addView(view)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多