How to send view to back ? How to control the z-order programmatically?

91,992

Solution 1

Afaik there's no built-in solution for this. I guess you're trying to modify the z-order in a FrameLayout, or something similar.

However, I think you can modify the order of the contained child elements in the layout. RemoveChild...() and addView() methods can take position values, so you could most likely swap child elements around, and that would modify the z-order. It seems a bit hacky solution however.

Or consider modifying the visibility property of the child views, you may get similar behaviour, and that'd be much cleaner I think.

Edit:

With the new Android version, the L Developer Preview it seems that at last we have the ability to easily change the Z ordering of Views. 'Elevation' and 'TranslationZ' properties to the rescue: https://developer.android.com/preview/material/views-shadows.html

Solution 2

I realize that this has been implied in other answers, but no one posted the code. I keep the following in a utility class where I have "helper" functions for dealing with views:

public static void sendViewToBack(final View child) {
    final ViewGroup parent = (ViewGroup)child.getParent();
    if (null != parent) {
        parent.removeView(child);
        parent.addView(child, 0);
    }
}

Solution 3

There is no sendToBack() method. But if you call bringToFront() on the lower positioned view you get almost the same effect.

Solution 4

Call bringToFront() on the view you want to get in the front, and then call the invalidate() method on all the view including the view which you want in the front. Repeat same for all the listeners.

So when another view's listener will get called, the previous view will get invalidated and will be in background.

Solution 5

Here is the method I am using to send a View to the back (so opposite of bringToFront, kind of sendToBack):

    private void moveToBack(View myCurrentView) 
    {
        ViewGroup myViewGroup = ((ViewGroup) myCurrentView.getParent());
        int index = myViewGroup.indexOfChild(myCurrentView);
        for(int i = 0; i<index; i++)
        {
            myViewGroup.bringChildToFront(myViewGroup.getChildAt(i));
        }
    }

Hope this helps!

Share:
91,992
Lukap
Author by

Lukap

Before I was user706780 :-),than Luk ,than ....

Updated on July 05, 2022

Comments

  • Lukap
    Lukap almost 2 years

    I have a problem to send the view to back. In Android we have a method like bringToFront(), to place the view on top of the another view. Like that, I want to put the view on below the previous image.

    Is there any method like sendToBack() or bringToBack() in Android. If so, can any one help me in this.

    Note: that I do not want to control the z-order by the order of placing items in layout I want to control the z-order programmatically.

    I do not want to hide the views on the front I just want them to be behind the view that is moving.