get Item Position in Adapter - Android User Interface

Android examples for User Interface:Adapter

Description

get Item Position in Adapter

Demo Code

/*//w w  w.j  a va 2  s.  c o  m
 * Copyright (C) 2014 Kamil Kalisz.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import android.widget.Adapter;

public class Main {
    public static final int INVALID_POSITION = -1;

    /**
     * @param adapter - adapter with objects to be searched 
     * @param object - object to search in adapter
     * @return position of item or -1 if item is not in adapter
     */
    public static int getItemPosition(Adapter adapter, Object object) {
        return getItemPosition(adapter, object, INVALID_POSITION);
    }

    /**
     *
     * @param adapter - adapter with objects to be searched 
     * @param object - object to search in adapter
     * @param defaultPosition - default position to return if object is not in adapter
     * @return position of item or default position if item is not in adapter
     */
    public static int getItemPosition(Adapter adapter, Object object,
            int defaultPosition) {
        int position = defaultPosition;
        for (int i = 0; i < adapter.getCount(); i++) {
            if (adapter.getItem(i).equals(object)) {
                position = i;
                break;
            }
        }
        return position;
    }
}

Related Tutorials