我有两个这样的RecyclerView,它们在我的片段中使用相同的适配器
RecyclerView rvFirst;
RecyclerView rvSecond;
ArrayList<Data> alFirst;
ArrayList<Data> alSecond;
AdapterBoth adapterFirst;
AdapterBoth adapterSecond;
...
rvFirst = (RecyclerView) myView.findViewById(R.id.rvFirst);
adapterFirst = new AdapterBoth(alFirst);
rvFirst.setAdapter(adapterFirst);
rvFirst.setLayoutManager(mLayoutFirst);
adapterFirst.setOnItemClickListner(new AdapterBoth.onItemClickListner() {
@Override
public void onClick(int id) {
showAcceptDialog(id, TYPE_ONE);
}
});
rvSecond = (RecyclerView) myView.findViewById(R.id.rvSecond);
adapterSecond = new AdapterBoth(alSecond);
rvSecond.setAdapter(adapterSecond);
rvSecond.setLayoutManager(mLayoutSecond);
adapterSecond.setOnItemClickListner(new AdapterBoth.onItemClickListner() {
@Override
public void onClick(int id) {
showAcceptDialog(id, TYPE_TWO);
}
});
我这样获取数据
private class JSONParse extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
...
jsonDataSet1 = data.getJSONArray("dataSet1");
jsonDataSet2 = data.getJSONArray("dataSet2");
for (int i = 0; i < jsonDataSet1.length(); i++) {
JSONObject o = jsonDataSet1.getJSONObject(i);
alFirst.add(new Data(o.getInt(TAG_ID), o.getString(TAG_DATE), o.getString(TAG_NAME)));
}
for (int i = 0; i < jsonDataSet2.length(); i++) {
JSONObject u = jsonDataSet2.getJSONObject(i);
alSecond.add(new Data(u.getInt(TAG_ID), u.getString(TAG_DATE), u.getString(TAG_NAME)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Void args) {
adapterFirst.notifyDataSetChanged();
adapterSecond.notifyDataSetChanged();
}
}
但是问题是两个RecyclerViews都显示相同的数据,或者更好地说是最后一个初始化的RecyclerView的数据(如果我交换适配器init的位置,则最后一个将在两个中显示)我可以看到不同的大小({ {1}})和其他数据(如果我做Log.d(ArrayList.size())
)
我确定每个RecyclerView都有不同的Adapter实例,但是它们的作用就像我在两者上设置相同。我认为这与RecyclerView有关,但我不确定
答案 0 :(得分:3)
在您的“ doInBackground”内部有一个错误,在第二个循环中,您正在使用变量“ u”,但从第一个循环中插入了变量“ o”中的值:
for (int i = 0; i < jsonDataSet1.length(); i++) {
JSONObject o = jsonDataSet1.getJSONObject(i);
alFirst.add(new Data(o.getInt(TAG_ID), o.getString(TAG_DATE), o.getString(TAG_NAME)));
}
for (int i = 0; i < jsonDataSet2.length(); i++) {
JSONObject u = jsonDataSet2.getJSONObject(i);
alSecond.add(new Data(o.getInt(TAG_ID), o.getString(TAG_DATE), o.getString(TAG_NAME)));
}
应该是:
for (int i = 0; i < jsonDataSet1.length(); i++) {
JSONObject o = jsonDataSet1.getJSONObject(i);
alFirst.add(new Data(o.getInt(TAG_ID), o.getString(TAG_DATE), o.getString(TAG_NAME)));
}
for (int i = 0; i < jsonDataSet2.length(); i++) {
JSONObject u = jsonDataSet2.getJSONObject(i);
alSecond.add(new Data(u.getInt(TAG_ID), u.getString(TAG_DATE), u.getString(TAG_NAME)));
}