I try to change the content of a Listview in Android. After that I want the list to be redrawn. Unfortunately the list elements change, but the old items are displayed in the background. If there are less items in the new list it seems like the old items are still part of the list, as they are still displayed, even though they are not clickable. If I jump out of the app via the Android Taskmanager and afterwards open the app again, the list gets displayed correctly! Therefore I think it must be a problem with refresh.
How do I try to achieve it:
As the complete content changes I create a new adapter that I pass to the ListView. In my code "favorites" is the new Array that I pass to the adapter. I also try to clear the list and invalidate it. all of this happens in the UI thread (onPostExecute of AsyncTask)
MyAdapter newAdapter = new MyAdapter(
context, favorites);
MyAdapter current_adapter = (MyAdapter) myList.getAdapter();
if((current_adapter!=null)){
current_adapter.clear();}
myList.setAdapter(null); //inserted this because of answers, but with no effect.
myList.setAdapter(newAdapter);
myList.invalidateViews();
The clear method of the adapter:
public void clear(){
items.clear();
notifyDataSetChanged();
}
As you can see I tried all of the solutions to similar problems her on stackoverflow. Unfortunately nothing worked...
Thanks in advance for any ideas how to solve this.
Edit:
I have also tried to set the adapter null before passing the new one, also with no effect. .setAdapter(null);
Also if I open the keyboard by clicking in a editText, the screen refreshs and the list is displayed correctly.
Have you tried myList.setAdapter(null);
?
I solved the problem by filling the remaining space under the list with a layout with more layout_weight
than the ListView
. This way the "extra" lines are hidden.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/transparent"
android:orientation="vertical" >
<ListView
android:id="@+id/main_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/aux_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/transparent"
android:orientation="vertical" />
</LinearLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With