I'm making an mp3 player app.
In order to better highlight which song is playing, I change the background color of the current song's listitem.
Everything works fine when I click on the actual list items using the onItemClickListener. I can also auto update to highlight the next song after the current one has finished.
However only when the next song list item is on screen. Same goes if I am on the first song and press back to go to the last song in the list. The song plays fine, but i get a null pointer exception on the list item when I try to set the background color.
Update color method: (I get the nullpointer on the last line #ff9966
public static void updateSongColor() {
if (currentSongPos == songs.size()-1) {
currentSongPos = 0;
}
else {
currentSongPos++;
}
currentSongView.setBackgroundColor(Color.parseColor("#FFFFFF"));
currentSongView = listView.getChildAt(currentSongPos);
currentSongView.setBackgroundColor(Color.parseColor("#ff9966"));
}
Maybe because it isn't inflated yet? I actually don't know.
How do I inflate or "load" the view I want to change color of dynamically?
I have tried:
.setSelection()
Before changing the background color, but that made no difference, I thought since I move to it, it will be "loaded" and thus not null.
This question is different from other similar ones because I want to know how I can "Pre-load" a view that is outside the screen and alter it's parameters (background color).
Here is my adapter class if it matters, and feel free to request more code snippets because I don't know what might be relevant here.
public class PlayListAdapter extends ArrayAdapter<Song> {
public PlayListAdapter(Context context, ArrayList<Song> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View row, ViewGroup parent) {
Song data = getItem(position);
row = getLayoutInflater().inflate(R.layout.layout_row, parent, false);
TextView name = (TextView) row.findViewById(R.id.label);
name.setText(String.valueOf(data));
row.setTag(data);
return row;
}
}
Thanks!
If I do, I update view in PlayListAdpater.
I'm adding variable for selected position in adapter.
And I'm changing it when next song play.
If you call 'updateSongColor' in Service, you can use broadcast or AIDL.
Example)
public class PlayListAdapter extends ArrayAdapter<Song> {
private int currentSongPos =-1; // init
...
public void setCurrentSong(int pos) {
currentSongPos = pos;
}
...
@Override
public View getView(int position, View row, ViewGroup parent) {
....
if(currentSongPos == position)
currentSongView.setBackgroundColor(Color.parseColor("#ff9966"));
else
currentSongView.setBackgroundColor(Color.parseColor("#FFFFFF"));
....
}
}
....
....
// call updateSongColor
public void updateSongColor() {
if (currentSongPos == songs.size()-1) {
currentSongPos = 0;
}
else {
currentSongPos++;
}
PlayListAdapter.setCurrentSong(currentSongPos);
PlayListAdapter.notifyDataSetChanged();
}
...