I'm trying to make a Music Player in Android, and yesterday I got the idea to set the currently playing song colored in the ListView.
At the beginning I set that every time I start a song, a new BaseAdapter inflate a layout with 2 TextView (title and artist) and if the song is the same in the MediaPlayer, the 2 TextView become blue.
It was working fine, but i noticed that when I pick a song, the ListView scrolls immediately up because the Adapter is recreated.
Searching the web I found that I could create a new method in the BaseAdapter class, where if I pass the ListView and the song position I could color it, so I would call the setAdapter(songList) only in the onCreate method.
Yeah, but it doesn't work.
-SongAdapter:
public void updateData(ListView listView, int position){
if (MainActivity.isMusicStarted) {
//These 2 lines of code return a NullPointerException
songView = (TextView) listView.getSelectedView().findViewById(R.id.song_title);
artistView = (TextView) listView.getSelectedView().findViewById(R.id.song_artist);
//The following 2 lines, if de-commented, color only the two TextView in the first shown row instead of the selected row
//songView = (TextView) listView.findViewById(R.id.song_title);
//artistView = (TextView) listView.findViewById(R.id.song_artist);
if (position==MusicService.getCurrentSong()) {
songView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
artistView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
else{
songView.setTextColor(ContextCompat.getColor(context, android.R.color.primary_text_light));
artistView.setTextColor(ContextCompat.getColor(context, android.R.color.secondary_text_light));
}
}
}
-MainActivity: (called at the end of a OnCompletitionListener())
public static void colorSongSelected(int position){
songAdapter.updateData(songView, position);
}