safe Add Child View - Android User Interface

Android examples for User Interface:View Child

Description

safe Add Child View

Demo Code


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class Main{
    public static void safeAddChildView(ViewGroup parent, View child,
            int index) {

        if (parent != null && child != null) {
            if (child.getParent() == null
                    && ViewUtil.safeIndexOfChild(parent, child) == -1) {
                parent.addView(child, index);

            }/* w  w  w  . j a va2 s  .  com*/
        }
    }
    /**
     * whether contains child
     *
     * @param parent
     * @param child
     * @return the index of the child if the parent contains the child, otherwise return -1
     */
    public static int safeIndexOfChild(ViewGroup parent, View child) {
        return (parent != null && child != null) ? parent
                .indexOfChild(child) : -1;
    }
}

Related Tutorials