2017-04-06 24 views
1

我在適配器上調用notifyItemRemoved(position)時遇到問題。每當我提供的位置不是最後一個元素,並且刪除動畫發生時,最後一個元素將在移動之前總是「閃爍/閃爍」,如下面的截圖(鏈接)所示。Android RecyclerView適配器notifyItemRemoved導致列表中的最後一個元素在動畫時閃爍

這裏是我的一小段代碼:

MainActivity.java

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // ... 

     RecylerView recyclerView = (RecyclerView) findViewById(R.id.list_view); 
     recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); 
     recyclerView.setItemAnimator(new DefaultItemAnimator()); 
     recyclerView.setAdapter(new ItemAdapter()); 
    } 

ItemAdapter.java

public void onBindViewHolder(final ViewHolder holder, int position) { 
     holder.mButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // mItems has a list of hard-coded elements 
       mItems.remove(holder.getAdapterPosition()); 
       notifyItemRemoved(holder.getAdapterPosition()); 
      } 
     }); 
    } 

content_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.myapp.myapplication.MainActivity" 
    tools:showIn="@layout/activity_main"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/list_view" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:scrollbars="vertical"> 
    </android.support.v7.widget.RecyclerView> 
</android.support.constraint.ConstraintLayout> 

list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 
    <Button 
     android:id="@+id/btn_click" 
     android:text="Delete" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

有沒有人通過這個走了,如何解決這個問題呢?

在此先感謝。

.gif of the issue

+0

你可以發佈佈局文件或'RecyclerView'嗎? – azizbekian

+0

@azizbekian對不起,我很忙。是的,這個xml已經被添加了。我沒有添加activity_main.xml,因爲它是在Android Studio中創建新項目時的默認xml – SuKhai

回答

0

在情況下,如果你不希望任何動畫,可以加入這一行

((DefaultItemAnimator) recyclerViewObject.getItemAnimator()).setSupportsChangeAnimations(false); 
+0

感謝您的提議,但我想要有動畫。 :) – SuKhai

+0

我給出的解決方案將只刪除項目添加和刪除的動畫。用於在recyclerview中添加和移除項目的默認動畫是淡入淡出,這就是爲什麼你會看到眨眼。你可以在這裏瞭解更多。 http://frogermcs.github.io/recyclerview-animations-androiddevsum​​mit-write-up/ – CodeCameo

+0

我試過了,但我仍然得到相同的結果...偉大的參考鏈接的方式 – SuKhai

0

添加到您的代碼。

recyclerView.getItemAnimator().setChangeDuration(0); 
+0

嗨@Faa我試過,但它沒有工作。問題仍然存在:( – SuKhai

相關問題