奇怪的LinearLayoutManager.scrollToPositionWithOffset(...)行为

时间:2015-12-02 18:56:21

标签: android android-recyclerview android-viewholder linearlayoutmanager

我有RecyclerView Adapter,其中包含两种不同的观点。第一个视图的宽度和高度略大于以下视图。

当开始包含RecyclerView的活动时,我想滚动到Adapter中的某个位置。我是通过致电与scrollToPositionWithOffset(position, offset)相关联的LinearLayoutManager上的RecyclerView来完成此操作的。

以下代码粗略描述了设置(没什么不寻常的)。包含RecyclerView调用Timeline.scrollTo(position)的活动。 请关注我发布Scala代码。

包含RecyclerView

的活动
class Activity extends [...] {

    lazy val timeline = findView( TR.layout_screen_transaction_timeline )

    override def onCreate( state: Option[Bundle] ) = {
        super.onCreate( state )

        setContentView( R.layout.screen_transaction_timeline )

        [...]

        timeline.setAdapter( adapter )

        if ( state.isEmpty ) {
            focus.foreach { position ⇒
                new Handler().post { () ⇒
                    timeline.scrollTo( position )
                }
            }
        }
    }

使用LinearLayoutManager的RecyclerView

class Timeline( attributes: AttributeSet = null, style: Int = 0 )( implicit context: Context )
    extends RecyclerView( context, attributes, style ) {
    [...]

    setHasFixedSize( true )
    setLayoutManager( layoutManager )

    def scrollTo( position: Int ) = {
        layoutManager.scrollToPositionWithOffset( position, 0 )
    }

    object layoutManager extends LinearLayoutManager( context, VERTICAL, false )
}

适配器

object adapter extends Adapter[Holder] {
    override def getItemCount = tour.shipments.length + 1

    override def onBindViewHolder( holder: Holder, position: Int ) = holder.view match {
        case collection: widget.transaction.timeline.Header ⇒
            collection.set( tour.collection, tour, tour.state == Tour.State.New )
        case waypoint: widget.transaction.timeline.Waypoint ⇒
            waypoint.set( position, tour.shipments( position - 1 ), focus.contains( position ) )
    }

    override def onCreateViewHolder( parent: ViewGroup, kind: Int ) = Holder {
        val view = kind match {
            case 0 ⇒ new widget.transaction.timeline.Header()
            case 1 ⇒ new widget.transaction.timeline.Waypoint()
        }

        view.setLayoutParams( new RecyclerView.LayoutParams( MATCH_PARENT, WRAP_CONTENT ) )
        view
    }

    override def getItemViewType( position: Int ) = position match {
        case 0 ⇒ 0
        case _ ⇒ 1
    }
}

除非我想滚动到最后位置,否则一切正常。 在这种情况下,LinearLayoutManager有时会正确地滚动到该位置,有时会略微偏离。

更新:我刚刚发现删除包含ActionBar的活动中的RecyclerView可以解决此问题。但是我需要ActionBar ...

enter image description here

0 个答案:

没有答案
相关问题