Search code examples
androidsimpleadapter

SimpleAdapter issue when changing the background of a button, it changes for all items


When im populating my SimpleAdapter. On the getView() method I check if a video already exists or not. If it already exists I will change the image of the button to a "Play" image. Otherwise, I will keep its "download" image. The problem is when I scroll the list, it changes all the buttons to "Play" images. This is my code, what im doing wrong?

public View getView(int position, View convertView, ViewGroup parent) {
    View row=super.getView(position, convertView, parent);

    TextView videoIdText = (TextView) row.findViewById(R.id.videoId);
    Button downloadButton = (Button) row.findViewById(R.id.videoDownload);

    final String videoId = videoIdText.getText().toString();

    if (videoExists(videoId)) {

        downloadButton.setBackgroundResource( R.drawable.ic_play );
        Drawable d =  downloadButton.getBackground();
        d.setColorFilter(Color.parseColor("#00AA00"),Mode.SRC_ATOP);

        downloadButton.setOnClickListener(new OnClickListener(){ 
            @Override
            public void onClick(View view) {
                if (activity !=null){
                    ((FeedActivity)activity).playVideo(getVideoPath(videoId));
                }       
            }
        });     
    }else{
        downloadButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
                DownloadTask task = new DownloadTask();
                task.setVideoId(videoId);
                task.execute();
            }
        });         
    }

Solution

  • In the else clause of your "if(videoExists(videoId))" you need to set the default "download" button image and color filter.

    This is because the items are reused when you scroll the list, so the buttons with the new settings will be reused with those new settings for other items that are not currently playing.


    Example:

    if (videoExists(videoId)) {
        downloadButton.setBackgroundResource( R.drawable.ic_play );
        Drawable d =  downloadButton.getBackground();
        d.setColorFilter(Color.parseColor("#00AA00"), Mode.SRC_ATOP);
        ...
    } else {
        downloadButton.setBackgroundResource( R.drawable.ic_download );
        Drawable d =  downloadButton.getBackground();
        d.setColorFilter(Color.parseColor("<download-color>"), Mode.SRC_ATOP);
        ...
    }