Updating GridView child

2019-08-02 06:05发布

问题:

I have a GridView loaded in an Activity with fragments present. The GridView itself is not located in a Fragment. I created a customer adapter by way of BaseAdapter and everything is working peachy.

CustomerAdapter.java

    @Override
public View getView( int position, View convertView, ViewGroup parent ) {

    ImageView v = new ImageView( activity );
    Bitmap bmp = getBitmap( videoIds[ position ] );
    v.setImageBitmap( bmp );
    v.setAdjustViewBounds( true );
    v.setPadding( 5, 5, 5, 5 );
    v.setId( position );

    thumbnails[ position ] = bmp;

    return v;

}

I have a contextual action bar that will allow you to select videos to be uploaded, deleted etc.

videoGallery.setChoiceMode( GridView.CHOICE_MODE_MULTIPLE_MODAL );
videoGallery.setMultiChoiceModeListener( new MultiChoiceModeListener() { ... }

I want to add a border around the video when it is selected so with the padding all I need to do is add a background color. So I have this in the new MultiChoiceModeListener() section listed above:

@Override
public void onItemCheckedStateChanged( ActionMode mode, int position, long id, boolean checked ) {
ImageView image = (ImageView)videoGallery.findViewById( position );
    if( checked ) {
        image.setBackgroundColor( Color.YELLOW );
    } else {
        image.setBackgroundColor( Color.TRANSPARENT );
    }
    int count = videoGallery.getCheckedItemCount();
    if( count == 1 ) {
        mode.setSubtitle( "1 item selected." );
    } else if( count != 0 ) {
        mode.setSubtitle( count + " items selected." );
    } else {
        mode.setSubtitle( null );
    }
}

The problem is that the child view does not update. The title gets updated "1 item selected, 2 items selected, etc.) so I know the method is being called. And setting the background does produce a background so it's not that I'm just not able to see the changes. The view itself is not updating. I've even set random IDs on the views when they are created and doing image.getId() provides the correct ID so I know it is finding the view. It is just not updating it. Any help?

回答1:

this doesn't seem right:

ImageView image = (ImageView)videoGallery.findViewById( position );

the reason : position is set to be 0<=position<=count-1 . the id is a totally different thing .

you need to update the raw data itself , and tell the adapter to update its views , for example using notifyDataSetChanged() .


EDIT:

that's not the only problem . the real problem is that you create a new ImageView for the getView() , always (this , btw, causes a memory leak since adapterView caches its created views ) , instead of recycling it . you should really watch the video "the world of listView" .

the reason that it doesn't work for you is that you access old views that aren't used anymore.