Search code examples
androidlistlistviewcursorbackground-color

Change list-view item background dynamically


I am having a list of songs and want to highlight(change background of) that song which is currently playing.It should be able to change background when my song finishes and goes to next one.I also want background to change when I select any list-view item. Can somebody please guide me on how to move forward with this. Code:-

I am implmenting this code but more than one list-item color is changing

@Override
public void bindView(View view, Context context, Cursor cursor) {
    // TODO Auto-generated method stub
    super.bindView(view, context, cursor);

    final View vi=inflater.inflate(layout, null, false);
    TextView titleS=(TextView)view.findViewById(R.id.TitleSong);
    TextView artistS=(TextView)view.findViewById(R.id.Artist);
    int Title_index;
    int Artist_index;



        Title_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
        Artist_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
        titleS.setText(cursor.getString(Title_index));
        artistS.setText(cursor.getString(Artist_index));

     if(cursor.getPosition()==MainActivity.songPosition){
         titleS.setBackgroundColor(Color.BLUE);
     }

}

Solution

  • I would suggest you to have a a field with the current song index in your adapter and depending on that index chose a background. Then when the song stops playing you probably have some kind of callback, so there you can increase this index and invoke notifyDataSetChange() on your adapter to redraw your views.

    And the last thing, when you select a list item, you should change current song index to the index of the selected item and also call notifyDataSetChange().

    Here is some code

    getView(int position, View convertView, ViewGroup parent) {
        //initialize view
    
        if (position == currentSongPosition) {
            yourView.setBackground(...);
        }
    
        yourView.setOnClickListener(new OnClickListener() {
              public void onClick(View view) {
                  currentSongPosition = position;
                  notifyDataSetChange();
              }
        });
    
    }