Inserts a View into a ViewGroup after directly before a given . - Android User Interface

Android examples for User Interface:ViewGroup

Description

Inserts a View into a ViewGroup after directly before a given .

Demo Code

// Copyright (c) 2013 The Chromium Authors. All rights reserved.
//package com.java2s;

import android.view.View;
import android.view.ViewGroup;

public class Main {
    /**/*from  w w  w  . java  2  s  .  c  o  m*/
     * Inserts a {@link View} into a {@link ViewGroup} after directly before a given {@View}.
     * @param container The {@link View} to add newView to.
     * @param newView The new {@link View} to add.
     * @param existingView The {@link View} to insert the newView before.
     * @return The index where newView was inserted, or -1 if it was not inserted.
     */
    public static int insertBefore(ViewGroup container, View newView,
            View existingView) {
        return insertView(container, newView, existingView, false);
    }

    private static int insertView(ViewGroup container, View newView,
            View existingView, boolean after) {
        // See if the view has already been added.
        int index = container.indexOfChild(newView);
        if (index >= 0)
            return index;

        // Find the location of the existing view.
        index = container.indexOfChild(existingView);
        if (index < 0)
            return -1;

        // Add the view.
        if (after)
            index++;
        container.addView(newView, index);
        return index;
    }
}

Related Tutorials