Skip to content Skip to sidebar Skip to footer

Accessing List's First Item When List View Is Loaded In Android

If there is no event like list.onLoadListener(list is done with its data filling) how to access list's first row? As list reuses its row for performance this listener is not there

Solution 1:

You can use Custom Adapter for List View and and then you can intercept the view on any specific position in public View getView(int position, View convertView, ViewGroup parent) method. Here you can check that

if(position==0){
 //do your stuff
}

Look this answer for Custom Adapter


Solution 2:

When are you populating the list? When do you want access to the first element? If you are using fragments you have onViewCreated, onCreateView methods and you can populate the listview in the onCreateView method and access to it in the onViewCreated methods. With activitys it is different, you could populate the list in onCreate() and later onStart() or onResume() access to the first element.


Solution 3:

Don't know if this is the best approach but you can give it a try.

Create a listener that looks something like this

public interface ViewLoadedInterface {
    public void onFirstViewLoaded(/**add params if you like*/);
}

Pass that Interface to your Adapter. You only invoke the onFirstViewLoaded() method when your first View is returned and then never invoke it again for that instance, otherwise you will have some problems when recycling starts.

When it is invoked you then do the list.getChildAt(0) in the implementation of the interface.

So in the end the implementation will look something like this

public class YourActivityClass extends Activity implements ViewLoadedInterface {
    ...

    @Override
    public void onFirstViewLoaded() {
        ...

        something = list.getChildAt(0);

        ...
    }
}

Solution 4:

I found the solution for this situation from this thread :- https://stackoverflow.com/a/6944587/647014

My requirement was to accessing list's first item as soon as list completes its data loading. This way list waits till its data is refreshed/loaded.

Thanks.


Post a Comment for "Accessing List's First Item When List View Is Loaded In Android"