views:

17

answers:

1

I'm currently making a SMS Application in Android, the following is a code snippet from Inbox Listactivity, I have requested a cursor from the contentresolver and used a custom adapter to add custom views into the list.

Now, in the custom view i've got 2 TextViews (tvFullBody,*tvBody*)... tvFullBody contains the Full SMS Text while tvBody contains a short preview (35 characters) The tvFullBody Visibility is by default set to GONE.

My idea is, when the user clicks on a list item, the tvBody should dissappear(GONE) and the tvFullBody should become visible (VISIBLE). On Clicking again, it should revert back to its original state.

//isExpanded is a BitSet of the size = no of list items...keeps track of which items are expanded and which are not

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    if(isExpanded.get(position))
    {
        v.findViewById(R.id.tvFullBody).setVisibility(View.GONE);
        v.findViewById(R.id.tvBody).setVisibility(View.VISIBLE);
    }else
    {
        v.findViewById(R.id.tvFullBody).setVisibility(View.VISIBLE);
        v.findViewById(R.id.tvBody).setVisibility(View.GONE);
    }
    isExpanded.flip(position);
    super.onListItemClick(l, v, position, id);
}

The Code works as it is supposed to :) except for an undesired sideeffect.... Every 10th (or so) List Item also gets "toggled". eg. If i Expand the 1st, then the 11th, 21th list items are also expanded...Although they remain off screen, but on scrolling you get to see the undesired "expansion".

By my novice analysis, i'm guessing Listview keeps track of 10 list items that are currently visible, upon scrolling, it "reuses" those same variables, which is causing this problem...(i didn't check the android source code yet.) I'd be gratefull for any suggestion, on how i should tackle this! :) I'm open to alternative methods aswell....Thanks in advance! :)

A: 

Your diagnosis of the problem almost correct. What's happening is that Android is reusing the Views it creates to display the list to save memory. Instead of creating a new View for every item in your list, Android creates just enough to fill the screen, updating them to show the relevant data for the items which are currently visible.

So when you show tvFullBody when the user clicks on an item, when that View is re-used later tvFullBody is still visible.

You may have to write you own ListAdapter to make sure the Views are displayed how you want. It should be as simple as extending the ListAdapter you are currently using and overriding the getView() method to ensure that tvFullBody is hidden.

Dave Webb
It was tricky but i managed to get it working :) Thanks for pointing me in the right direction!
st0le