0

学校のプロジェクト用に Android アプリケーションをコーディングしています。

RecyclerViewを使用して水平スクロールを実装しましたLinearLayoutManager.HORIZONTAL

次のように、要素 n などの特定の要素が、現在表示されている要素のセットの 真ん中にあるようにしたいと思います。ここに画像の説明を入力

私は周りを検索して、このリンクを見つけました: https://www.reddit.com/r/androiddev/comments/3o0xzw/how_do_you_scroll_to_an_item_with_recyclerview_to/

layoutManager.findFirstVisibleItemPosition()解決策は、 andの合計の半分を取り、layoutManager.findLastVisibleItemPosition()それを真ん中にしたい要素の位置に追加することでした。

RecyclerView.NO_POSITIONただし、この水平スクロールを使用すると、これらの 2 つのメソッドは常に返されるRecyclerViewため、合計の半分が 0 になり、計算が役に立たなくなります。

これが私のコードです:

RecyclerView selectDay = (RecyclerView) findViewById(R.id.lv_selectDay);
    daySelectorAdapter adapter = new daySelectorAdapter(this, arrayList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    selectDay.setAdapter(adapter);
    selectDay.setLayoutManager(layoutManager);

    int firstVisible = layoutManager.findFirstVisibleItemPosition();
    Log.d("FIRSTVISIBLE", String.valueOf(firstVisible)); // returns -1

    int lastVisible = layoutManager.findLastVisibleItemPosition();
    Log.d("LASTVISIBLE", String.valueOf(lastVisible)); // also -1

    int halfScreenOffset = (lastVisible - firstVisible) / 2;
    Log.d("HALFOFFSET", String.valueOf(halfScreenOffset));

    layoutManager.scrollToPositionWithOffset((15 + halfScreenOffset), 0);

誰かがこの問題の回避策を持っているかどうか教えてもらえますか? 前もって感謝します。

編集: aonScrollListenerと へのキャストrecyclerView.getLayoutManager()を実装しようとしたときLinearLayoutManager、これらのメソッドは完全に正常に機能しました。理由がわかりますか?

編集2:

ここでこのソリューションを使用しました: RecyclerView SmoothScroll を中央に配置します。android、しかし、なぜメソッドが返されるのNO_POSITIONですか?

4

0 に答える 0