簡體   English   中英

RecyclerView Adapter notifyDataSetChanged()之后未調用onBindViewHolder

[英]onBindViewHolder not called after RecyclerView Adapter notifyDataSetChanged()

我從Firebase數據庫中獲取了一些數據,並試圖用它填充RecyclerView適配器。 調用Adapter的notifyDataSetChanged()之后,屏幕閃爍並且什么都沒發生,我什至無法在onBindViewHolder中捕獲斷點。

這是我的代碼:

POJO類:

public class Result2 implements Serializable {

private int score;
private String userName;

public Result2(int score, String userName) {
    this.score = score;
    this.userName = userName;
}

public int getScore() {
    return score;
}


public String getUserName() {
    return userName;
}

}

這是我的活動布局,稱為activity_results.xml,其中包含RecyclerView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:weightSum="2">

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="USERNAME"
        android:textColor="#000"
        android:textSize="16sp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="SCORE"
        android:textColor="#000"
        android:textSize="16sp"/>

</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000"
    />

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
                                        xmlns:app="http://schemas.android.com/apk/res-auto"
                                        android:id="@+id/recycler_view"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:clipToPadding="false"
                                        android:paddingTop="10dp"
                                        android:scrollbars="vertical"
                                        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

這是我的Adapters ViewHolder布局,名為score_view_holder.xml。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="50dp"
              android:orientation="horizontal"
              android:weightSum="2">

    <TextView
        android:id="@+id/username"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="14sp"/>

    <TextView
        android:id="@+id/score"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="14sp"/>


</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginEnd="10dp"
    android:layout_marginStart="10dp"
    android:background="#4545"/>

因此,它將在下面包含兩個水平的TextViews和一個View。

這是我的適配器:

public class ScoreAdapter extends RecyclerView.Adapter<ScoreAdapter.ScoreViewHolder> {

private List<Result2> results = new ArrayList<>();

public void setResults(List<Result2> results) {
    this.results.clear();
    this.results.addAll(results);
    notifyDataSetChanged();
}

@Override
public ScoreAdapter.ScoreViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.score_view_holder, parent, false);
    return new ScoreAdapter.ScoreViewHolder(view);
}

@Override
public void onBindViewHolder(ScoreAdapter.ScoreViewHolder holder, int position) {
    Result2 result = getResult(position);
    if (result != null) {
        holder.setUsername(result.getUserName() != null ? result.getUserName() : "-");
        holder.setScore(String.valueOf(result.getScore()));
    }
}

private Result2 getResult(int position) {
    return !results.isEmpty() ? results.get(position) : null;
}

@Override
public int getItemCount() {
    return results.size();
}

public class ScoreViewHolder extends RecyclerView.ViewHolder {

    private TextView username;
    private TextView score;

    public ScoreViewHolder(View itemView) {
        super(itemView);
        username = itemView.findViewById(R.id.username);
        score = itemView.findViewById(R.id.score);
    }

    public void setUsername(String username) {
        this.username.setText(username);
    }

    public void setScore(String score) {
        this.score.setText(score);
    }

}
}

它應該獲取Result2對象的List並僅在這兩個TextViews中設置文本(用戶名和分數)

最后是我要從中通知適配器的活動:

public class Results extends AppCompatActivity {

private DatabaseReference mDatabase;
private ScoreAdapter scoreAdapter;
private RecyclerView recyclerView;
private List<Result2> results = new ArrayList<>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results);

    recyclerView = findViewById(R.id.recycler_view);
    scoreAdapter = new ScoreAdapter();
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(scoreAdapter);

    mDatabase = FirebaseDatabase.getInstance().getReference();

    loadResults();
}

private void loadResults() {

    mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
                                                       @Override
                                                       public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                                                           for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                                                               Result2 result = childSnapshot.getValue(Result2.class);

                                                               if (result != null) {
                                                                   results.add(result);
                                                               }
                                                           }
                                                           Toast.makeText(Results.this, String.valueOf(results.size()), Toast.LENGTH_SHORT).show();
                                                           scoreAdapter.setResults(results);

                                                       }

                                                       @Override
                                                       public void onCancelled(@NonNull DatabaseError databaseError) {

                                                       }
                                                   }

    );
}
}

所以在for循環完成之后,Toast顯示正確的結果數,調用了適配器setResults方法,在那里我接收到正確的結果數,這是一張圖片:

setResults()中的結果列表

但是,在調用notifyDataSetChanged()之后,屏幕僅閃爍並且所有內容均為空白...在它們上設置斷點后,無法訪問onBindViewHolder中的方法。.知道這里有什么問題嗎?

您的代碼中有幾個問題。 第一個是您正在調用setResults()方法,並將results列表傳遞到ScoreAdapter類內,而不是傳遞給ScoreAdapter 為了解決這個問題,請將您的setResults()方法更改為如下所示的構造函數:

public ScoreAdapter(List<Result2> results) {
    this.results.clear();
    this.results.addAll(results);
    notifyDataSetChanged();
}

還必須實例化適配器,並將其設置到回調中的RecyclerView 因此,要解決此問題,只需移動以下代碼行:

ScoreAdapter scoreAdapter = new ScoreAdapter(result);
recyclerView.setAdapter(scoreAdapter);

在以下行之后:

Toast.makeText(Results.this, String.valueOf(results.size()), Toast.LENGTH_SHORT).show();

也不要忘記注釋以下代碼行: scoreAdapter.setResults(results);

現在看,要實例化適配器,您需要將result列表傳遞給構造函數。

另外,請不要忘記將public no-argument constructor到您的Result2類。 在這里查看更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM