Java – Sets the maximum number of rows for the ListView

Sets the maximum number of rows for the ListView… here is a solution to the problem.

Sets the maximum number of rows for the ListView

This is a question about Android programming. I need to limit the maximum number of rows visible in a ListView.

In the onCreate method, I have the next code for my ListView:

listView.setAdapter(new ArrayAdapter<String>(this, android. R.layout.simple_list_item_1, arrayListOfElements));

In the onPostExecute method I have the next adapter:

ArrayAdapter<String> adapter = (ArrayAdapter<String>) arrayListOfElements.getAdapter();
adapter.notifyDataSetChanged();

So I need to set the maximum number of rows for my adapter, and I don’t care if the ListView is scrollable or not. Any ideas?

Solution

Do this in your base adapter (mList is the list of items you want to display in the ListView):

public int getCount() {
    if (mList != null) {
        return Math.min(mList.size(), YOU_MAX_VALUE);
    } else {
        return 0;
    }
}

Related Problems and Solutions