Вы можете найти более подробную документацию на главном сайте: https://advancedrecyclerview.h6ah4i.com
и копируются из swipeable страницы в документации следующее:
Шаг 1. адаптер поддерживает стабильное Идентификаторы
Этот шаг очень важен. Если адаптер не возвращает стабильные & уникальных идентификаторов, которые будут вызывать некоторые странные поведения (неправильные анимации, NPE, и т.д ...)
class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
MyAdapter() {
setHasStableIds(true);
}
@Override
public long getItemId(int position) {
// requires static value, it means need to keep the same value
// even if the item position has been changed.
return mItems.get(position).getId();
}
}
Шаг 2. Изменение макет файл представление элементов
Обнаружить просмотр контента другим FrameLayout
whitch имеет @+id/container
ID.
<!-- for itemView -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="56dp">
<!-- Content View(s) -->
<TextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</FrameLayout>
⏬ ⏬ ⏬
<!-- for itemView -->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="56dp">
<!-- for getSwipeableContainerView() -->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Content View(s) -->
<TextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"/>
</FrameLayout>
</FrameLayout>
Шаг 3. Изменить ViewHolder
- Изменить родительский класс для
AbstractSwipeableItemViewHolder
.
- Внедрение
getSwipeableContainerView()
метод.
Примечание: AbstractSwipeableItemViewHolder
класс является классом удобства, который реализует методы boilerplace из `SwipeableItemViewHolder.
⏬ ⏬ ⏬
class MyAdapter ... {
static class MyViewHolder extends AbstractSwipeableItemViewHolder {
TextView textView;
FrameLayout containerView;
public MyViewHolder(View v) {
super(v);
textView = (TextView) v.findViewById(android.R.id.text1);
containerView = (FrameLayout) v.findViewById(R.id.container);
}
@Override
public View getSwipeableContainerView() {
return containerView;
}
}
}
Шаг 4. Реализация интерфейса SwipeableItemAdapter
class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
...
}
⏬ ⏬ ⏬
class MyAdapter
extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
implements SwipeableItemAdapter<MyAdapter.MyViewHolder> {
@Override
public int onGetSwipeReactionType(MyViewHolder holder, int position, int x, int y) {
// Make swipeable to LEFT direction
return Swipeable.REACTION_CAN_SWIPE_LEFT;
}
@Override
public void onSetSwipeBackground(MyViewHolder holder, int position, int type) {
// You can set background color/resource to holder.itemView.
// The argument "type" can be one of the followings;
// - Swipeable.DRAWABLE_SWIPE_NEUTRAL_BACKGROUND
// - Swipeable.DRAWABLE_SWIPE_LEFT_BACKGROUND
// (- Swipeable.DRAWABLE_SWIPE_UP_BACKGROUND)
// (- Swipeable.DRAWABLE_SWIPE_RIGHT_BACKGROUND)
// (- Swipeable.DRAWABLE_SWIPE_DOWN_BACKGROUND)
if (type == Swipeable.DRAWABLE_SWIPE_LEFT_BACKGROUND) {
holder.itemView.setBackgroundColor(Color.YELLOW);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
}
@Override
public SwipeResultAction onSwipeItem(MyViewHolder holder, int position, int result) {
// Return sub class of the SwipeResultAction.
//
// Available base (abstract) classes are;
// - SwipeResultActionDefault
// - SwipeResultActionMoveToSwipedDirection
// - SwipeResultActionRemoveItem
// - SwipeResultActionDoNothing
// The argument "result" can be one of the followings;
//
// - Swipeable.RESULT_CANCELED
// - Swipeable.RESULT_SWIPED_LEFT
// (- Swipeable.RESULT_SWIPED_UP)
// (- Swipeable.RESULT_SWIPED_RIGHT)
// (- Swipeable.RESULT_SWIPED_DOWN)
if (result == Swipeable.RESULT_LEFT) {
return new SwipeResultActionMoveToSwipedDirection() {
// Optionally, you can override these three methods
// - void onPerformAction()
// - void onSlideAnimationEnd()
// - void onCleanUp()
};
} else {
return new SwipeResultActionDoNothing();
}
}
}
Шаг 5. Процесс инициализации Modify из RecyclerView
Поместите некоторый дополнительный процесс инициализации в вашем Activity
/Fragment
.
- Номер объекта
RecyclerViewSwipeManager
.
- Создайте обернутый адаптер и установите его на
RecyclerView
.
- Приложить
RecyclerView
к RecyclerViewSwipeManager
.
void onCreate() {
...
RecyclerView recyclerView = findViewById(R.id.recyclerView);
MyAdapter adapter = new MyAdapter();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
⏬ ⏬ ⏬
void onCreate() {
...
RecyclerView recyclerView = findViewById(R.id.recyclerView);
RecyclerViewSwipeManager swipeManager = new RecyclerViewSwipeManager();
MyAdapter adapter = new MyAdapter();
RecyclerView.Adapter wrappedAdapter = swipeManager.createWrappedAdapter(adapter);
recyclerView.setAdapter(wrappedAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// disable change animations
((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
swipeManager.attachRecyclerView(recyclerView);
}
Я надеюсь, что мой ответ поможет.
Я не могу найти документацию, когда я добавил зависимость от проекта. Он говорит очень хорошо, что он может сделать, используя пример приложения, но когда дело доходит до его использования ... Я потерял. Надеюсь, что вы найдете того, кто знает больше об этой библиотеке, я собираюсь попробовать альтернативы:/ – Jethro
Существует [альтернатива] (https://github.com/davideas/FlexibleAdapter/wiki) с несколько лучшей документацией. –
Ничего себе, я думаю, это может быть ответом на мои вопросы и желания! Похоже, что это очень документировано, но я еще не посмотрел на него. Большое спасибо. Если вы хотите, сделайте свой комментарий ответом. – iBobb