Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an android ListView, how can I iterate/manipulate all the child views, not just the visible ones?

The code below does NOT change the text of all of a ListView's rows because getChildCount() does not get all of a ListView's rows, but just the rows that are visible.

for (int i = 0; i < listView.getChildCount(); i++)
{
    View v = listView.getChildAt(i);
    TextView tx = (TextView) v.findViewById(R.id.mytext);
    tx.setTextSize(newTextSize);
}

So, what SHOULD I do?

Is there code for getting a notification when a ListView's row becomes visible, so I can set its text size then?

like image 493
Corey Trager Avatar asked Jan 22 '10 01:01

Corey Trager


2 Answers

In a ListView the only children are the visible ones. If you want to do something with "all the children," do it in the adapter. That's the best place.

like image 63
Romain Guy Avatar answered Nov 07 '22 07:11

Romain Guy


List13 from the API Demos does something similar using OnScrollStateChanged. There may be a better way, though:

public void onScrollStateChanged(AbsListView view, int scrollState) {
    switch (scrollState) {
    case OnScrollListener.SCROLL_STATE_IDLE:
        mBusy = false;

        int first = view.getFirstVisiblePosition();
        int count = view.getChildCount();
        for (int i=0; i<count; i++) {
            TextView t = (TextView)view.getChildAt(i);
            if (t.getTag() != null) {
                t.setText(mStrings[first + i]);
                t.setTag(null);
            }
        }

        mStatus.setText("Idle");
        break;

. . .

EDIT BY Corey Trager:

The above definitely pointed me in the right direction. I found handling OnScrollListener.onScroll worked better than onScrollStateChanged. Even if I removed the case statement in onScrollSgtaetChanged and handled every state change, some text wasn't getting resized. But with onScroll, things seem to work.

So, my seemingly working code looks like this:

public void onScroll(AbsListView v, int firstVisibleItem, int visibleCount, int totalItemCount)
{
    ListView lv = this.getListView();
    int childCount = lv.getChildCount();

    for (int i = 0; i < childCount; i++)
    {
        View v = lv.getChildAt(i);
        TextView tx = (TextView) v.findViewById(R.id.mytext);
        tx.setTextSize(textSize);
    }
}
like image 23
RickNotFred Avatar answered Nov 07 '22 06:11

RickNotFred