JonDal
JonDal

Reputation: 93

Change appearance of a single view in a ListView

I'm working on a music app. I want to bold the information of the song which is currently playing (ex. Google Play Music). There is a ListView of all songs, populated by a RelativeLayout of song info for each song. A song is played either by clicking on the ListView (which can play any song) or pressing previous or next (which will play an adjacent song).

I dont want to use a ScrollView because the song library could have a very large number of entries to display.

I need to be able to

I've look at GPM source code here but I couldn't tell where it does this. Any help would be GREATLY appreciated :)

Upvotes: 0

Views: 66

Answers (1)

Ben P.
Ben P.

Reputation: 54204

Regardless of whether you use ListView or RecyclerView, the general template of the solution will be the same: you should store a reference to either (a) the "currently playing" index or (b) the "currently playing" data item.

Let's look at what the solution would be if you were using ListView and saving the "currently playing" index.

Step one would be some variable to save what's currently playing. Maybe you use an int and treat the special value -1 as meaning that nothing is playing.

private int currentlyPlayingPosition;

Whenever you change whatever song is currently playing, you update the value stored here (maybe ++currentlyPlayingPosition when the user presses "next song", etc). You'll then also have to call adapter.notifyDataSetChanged() to tell the ListView to re-draw itself so that the bolded song changes.

In your getView() method, you can check to see if the view you're drawing is the "currently playing" song, and change the typeface based on that:

@Override
public View getView(int position, View convertView, ViewGroup container) {
    ...
    if (position == currentlyPlayingPosition) {
        textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
    } else {
        textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);
    }
    ...
}

The overall steps are relatively simple:

  • Track which song is currently playing (by index, by object reference, or some other way)
  • Any time the currently-playing song changes, notify the adapter
  • Inside getView() check if the song you're displaying is the currently-playing song, and show special UI if so

Upvotes: 1

Related Questions