Android Studio – Java – сложность выделения цвета фона элемента ListViewAndroid

Форум для тех, кто программирует под Android
Ответить
Гость
 Android Studio – Java – сложность выделения цвета фона элемента ListView

Сообщение Гость »


Introduction:

I am encountering an issue with highlighting the background color of ListView items in my Android application. Despite my attempts to modify the background color programmatically, the changes are not reflected in the UI.

Problem Description:

I am trying to dynamically change the background color of ListView items based on certain conditions, such as matching a specific song name. However, even though my code executes without errors and logs indicate that the matching logic is functioning correctly, the UI does not reflect the changes. The background color remains unchanged.

Initialization of ListView and Adapter:

ListView songsListView = findViewById(R.id.songsListView); SongsAdapter songsAdapter = new SongsAdapter(context, songNames); songsListView.setAdapter(songsAdapter); Attempt to Change Background Color within Loop:

// Find and highlight the song using the adapter for (int i = 0; i < songsAdapter.getCount(); i++) { String tempSongName = songsAdapter.getItem(i); // Log information about the song Log.d("SttList", "(SetListMasterViewActivity) line #222 - ChildViewInfo - Child view index: " + i); Log.d("SttList", "(SetListMasterViewActivity) line #223 - ChildViewInfo - tempSongName: " + tempSongName + ", lastViewedSongName: " + (i + 1) + ") " + lastViewedSongName); // Check if the song name matches the last viewed song name if (tempSongName != null && tempSongName.equalsIgnoreCase((i + 1) + ") " + lastViewedSongName)) { // Highlight the corresponding ListView item View childView = songsAdapter.getView(i, null, songsListView); if (childView instanceof TextView) { TextView textView = (TextView) childView; textView.setBackgroundColor(Color.YELLOW); // Log the match Log.d("SttList", "(SetListMasterViewActivity) line #226 - ChildViewInfo - Match found for song: " + lastViewedSongName); // Exit the loop once the match is found break; } } } xml:

In my adapter class - SongListAdapter:

@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_song, parent, false); } // Get the item for this position String songName = getItem(position); // Find views in the layout TextView itemNumberTextView = convertView.findViewById(R.id.itemNumberTextView); TextView songNameTextView = convertView.findViewById(R.id.songNameTextView); // Set the song number itemNumberTextView.setText((position + 1) + ")"); // Set the song name songNameTextView.setText(songName); // Set background color int backgroundColor = mBackgroundColors.get(position, 0); // Default is transparent convertView.setBackgroundColor(backgroundColor); return convertView; } I Have Tried:

Trying to change the background color from the Adapter class:

public void updateItemBackground(int position, int color) { mBackgroundColors.put(position, color); notifyDataSetChanged(); } with the adapter defined at the class level:

private SongListAdapter adapter;` and populated here:

adapter = new SongListAdapter(this, songNames); and being used to call the updateItemBackground method here, from within my loop:

if (childView instanceof TextView) { adapter.updateItemBackground(i, Color.YELLOW); // Log the match Log.d("SttList", "(SetListMasterViewActivity) line #226 - ChildViewInfo - Match found for song: " + lastViewedSongName); // Exit the loop once the match is found break; } But I got a NullPointerException error. Here is the Logcat data from the error:

E FATAL EXCEPTION: main Process: com.enetapplications.songtracker, PID: 5719 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=614906370, result=-1, data=Intent { (has extras) }} to activity {com.enetapplications.songtracker/com.enetapplications.songtracker.opensetlist.SetListMasterViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enetapplications.songtracker.opensetlist.SongListAdapter.updateItemBackground(int, int)' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:5864) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5903) at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54) at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2438) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8663) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.enetapplications.songtracker.opensetlist.SongListAdapter.updateItemBackground(int, int)' on a null object reference at com.enetapplications.songtracker.opensetlist.SetListMasterViewActivity.onActivityResult(SetListMasterViewActivity.java:238) at android.app.Activity.dispatchActivityResult(Activity.java:8659) at android.app.ActivityThread.deliverResults(ActivityThread.java:5857) Thank you for reading!


Источник: https://stackoverflow.com/questions/780 ... ound-color
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»