【问题标题】:RecyclerView insert animation with count from arrayListRecyclerView 使用 arrayList 中的计数插入动画
【发布时间】:2016-05-26 04:45:47
【问题描述】:

我有一个RecyclerView 和一个从数据库中检索到的数据,但由于

,无法显示插入动画

“检测到不一致。无效的视图支架适配器”。

我正在使用ArrayList 从数据库中检索一些项目,如下所示:

 /* Retrive  data from database */
public List<AudioItem> getDataFromDB(){
    List<AudioItem> audioList = new ArrayList<>();
    String query = "select * from " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query,null);

    if (cursor.moveToFirst()){
        do {
            AudioItem audio = new AudioItem();
            audio.setId(Integer.parseInt(cursor.getString(0)));
            audio.setName(cursor.getString(1));
            audio.setFilePath(cursor.getString(2));
            audio.setLength(Integer.parseInt(cursor.getString(3)));
            audio.setTime(Long.parseLong(cursor.getString(4)));
            audioList.add(audio);

        }while (cursor.moveToNext());
        cursor.close();
    }

    return audioList;
}

然后我将从 DB 检索到的 arrayList 传递给一个活动。还有另一个名为“itemList”的arrayList 用于过滤从DB 检索到的数据。然后将归档的数据从“itemList”传递到 RecyclerView 进行显示。代码如下:

    db = new DatabaseHelper(this);
    dbList = new ArrayList<>();
    dbList = db.getDataFromDB();


    itemList = new ArrayList<>();
    for (int i=0; i<dbList.size(); i++) {
        if (dbList.get(i).getName().contains(titleName))
            itemList.add(dbList.get(i));
    }

    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    mRecyclerView.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);

    //newest to oldest order (database stores from oldest to newest)
    llm.setReverseLayout(true);
    llm.setStackFromEnd(true);

    mRecyclerView.setLayoutManager(llm);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    adapter = new RecyclerAdapter(this, llm, itemList);
    mRecyclerView.setAdapter(adapter);

我的 RecyclerAdapter 的 notifyItemInserted 函数:

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

@Override
public void onNewDatabaseEntryAdded() {
    //item added to top of the list
    Log.e("Count: ", Integer.toString(getItemCount()));
    notifyItemInserted(getItemCount() - 1);
    llm.scrollToPosition(getItemCount() - 1);
}

我通知问题来自ArrayList 的getItemCount,但我不知道如何解决它。

【问题讨论】:

    标签: java android arraylist android-recyclerview


    【解决方案1】:

    类似于https://stackoverflow.com/a/32535796/3546306。只需尝试替换下一行代码:

    notifyItemInserted(getItemCount() - 1);
    

    通过这个:notifyDataSetChanged(getItemCount());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 2011-10-13
      相关资源
      最近更新 更多