Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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/

like image 393
Daniel Avatar asked Oct 08 '11 19:10

Daniel


People also ask

How can use multiple layouts in one activity in Android?

You can use as many layouts as possible for a single activity but obviously not simultaneously. You can use something like: if (Case_A) setContentView(R. layout.

Is it possible to include one layout definition in another?

To efficiently re-use complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.


2 Answers

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);
like image 84
Knickedi Avatar answered Sep 28 '22 03:09

Knickedi


((ViewGroup)view.getParent()).removeView(view);
newContainer.addView(view)
like image 42
Khaled AbuShqear Avatar answered Sep 28 '22 03:09

Khaled AbuShqear