Find the index/position of a view within its parent - Android User Interface

Android examples for User Interface:View Parent

Description

Find the index/position of a view within its parent

Demo Code


//package com.java2s;

import android.support.annotation.NonNull;

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

public class Main {
    /**/*w w w  .j a  va  2 s  . com*/
     * Find the index/position of a view within its parent
     *
     * @param view the input view
     * @return the index/position of the input view within its parent, or -1 if it doesn't have a parent
     */
    public static int getPositionInParent(@NonNull View view) {
        ViewParent parentView = view.getParent();
        if (parentView != null && parentView instanceof ViewGroup) {
            return ((ViewGroup) parentView).indexOfChild(view);
        } else {
            return -1;
        }
    }
}

Related Tutorials