私はAndroidで音楽プレーヤーを作ろうとしていて、昨日ListViewで現在再生中の曲を設定する考えがありました。Android:ListViewの選択した行の2つのTextViewを色づける方法
最初に曲を開始するたびに、新しいBaseAdapterが2 TextView(タイトルとアーティスト)のレイアウトを展開し、MediaPlayerで同じ曲があれば2 TextViewが青色になります。
うまくいきましたが、曲を選ぶと、アダプタが再作成されたため、リストビューがすぐにスクロールしてしまうことに気付きました。
Webを検索する私はBaseAdapterクラスで新しいメソッドを作成することができました.ListViewとソングの位置を渡すと色付けできるので、setAdapter(songList)はonCreateメソッドでのみ呼び出します。
ええ、でも動作しません。
-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:
public static void colorSongSelected(int position){
songAdapter.updateData(songView, position);
}