使用SmoothScroller时一次可单击单个项目

时间:2018-10-28 19:06:18

标签: android android-recyclerview

我有以下Github示例:A sample to showcase contact list divided into sections with group header

在Adapter类中,当用户单击某个项目时,我有以下代码:

boolean expanded = contact.isExpanded();
contact.setExpanded(!expanded);
notifyItemChanged(getAdapterPosition());

if (contact.isExpanded()) {
      mSmoothScroller.setTargetPosition(getAdapterPosition());
      new Handler().postDelayed(() ->
         mRecyclerView.getLayoutManager().startSmoothScroll(mSmoothScroller), 100);
}

当我同时单击两个具有childViews的项目时,出现以下异常:

java.lang.IllegalArgumentException: Invalid target position
        at android.support.v7.widget.RecyclerView$SmoothScroller.start(RecyclerView.java:11377)
        at android.support.v7.widget.RecyclerView$LayoutManager.startSmoothScroll(RecyclerView.java:8090)
        at com.sample.android.contact.ContactsAdapter$ViewHolder.lambda$onClick$0$ContactsAdapter$ViewHolder(ContactsAdapter.java:375)
        at com.sample.android.contact.ContactsAdapter$ViewHolder$$Lambda$0.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

我不想删除Handler.postDelayed,而是在寻找一种解决方案,一次只能单击单个项目?

1 个答案:

答案 0 :(得分:1)

我通过将setTargetPosition移到Handler.PostDelayed来解决问题:

new Handler().postDelayed(() -> {
                    mSmoothScroller.setTargetPosition(getAdapterPosition());
                    mRecyclerView.getLayoutManager().startSmoothScroll(mSmoothScroller);
                }, 100);