Я пытаюсь настроить свой recyclerview внутри viewpager2 и получить позицию для onclicklistener. Затем передайте это для привязки данных в xml.
Некоторые ссылки, которые я прочитал:
получить позицию выбранного элемента в recyclerView с помощью привязки данных
Я пробовал следующие методы:
- Используйте getAdapterPosition в просмотрщике. я всегда возвращаю 0
class myViewholder extends RecyclerView.ViewHolder{
Binding binding;
public myViewholder(@NonNull Binding itemView) {
super(itemView.getRoot());
this.binding = itemView;
binding.setPosition(getAdapterPosition());
}
}
- используйте «позицию» в onBindViewHolder. позиция возврата не всегда совпадает. это может быть 0->1->2->3->6->3 и т. д.
@Override
public void onBindViewHolder(@NonNull myViewholder holder, int position) {
binding.setPosition(position);
}
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:liftOnScroll="true">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways|snap">
//toolbar content
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
//recyclerview inside the viewpager
/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>