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

Android examples for User Interface:ViewGroup

Description

Inserts a View into a ViewGroup after directly after 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 www  .  j  a va 2s  .  c  o m*/
     * Inserts a {@link View} into a {@link ViewGroup} after directly after 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 after.
     * @return The index where newView was inserted, or -1 if it was not inserted.
     */
    public static int insertAfter(ViewGroup container, View newView,
            View existingView) {
        return insertView(container, newView, existingView, true);
    }

    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