Reparent a view in Android - move from one layout to another

前端 未结 2 1105
抹茶落季
抹茶落季 2021-02-05 03:25

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

2条回答
  •  盖世英雄少女心
    2021-02-05 04:02

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

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

提交回复
热议问题