我正在尝试在向左/向右滑动时显示自定义视图(或图像)。
我已经接近让它工作了,但是我在使用自定义图像时遇到了问题。
我想要的效果与此类似:RecyclerView ItemTouchHelper swipe remove animation
看看下面发生了什么。它在刷卡时扭曲图像:
下面是我的代码:
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
View itemView = viewHolder.itemView;
Paint p = new Paint();
if (dX > 0) {
Drawable d = ContextCompat.getDrawable(getActivity(), R.drawable.test_check);
d.setBounds(itemView.getLeft(), itemView.getTop(), (int) dX, itemView.getBottom());
d.draw(c);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
如何在继续绘制背景色时保持图像的静态?甚至可以使用android视图而不是图像吗?与此类似:https://github.com/wdullaer/SwipeActionAdapter
最佳答案
您可以准备Recycler视图项布局以包含复选标记ImageView
,也可以准备另一个只有背景色的空白视图。您还应该将所有可滑动内容移动到嵌套布局中。为视图保持架中的可切换内容分配一个引用。然后在setTranslationX
中的可滑动内容上调用onChildDraw
,例如:
((MyViewHolder) viewHolder).swipeableContent.setTranslationX(dX);
用源代码更新示例:
回收器视图项布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="@dimen/recycler_view_item_height"
android:background="@color/transparent">
<!-- background color view -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/purple" />
<!-- check symbol image view -->
<ImageView
android:layout_width="match_parent"
android:layout_height="@dimen/check_symbol_width"
android:contentDescription="@null"
android:src="@drawable/check_symbol" />
<!-- swipeable content container -->
<LinearLayout
android:id="@+id/swipeable_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- here goes your swipeable content -->
</LinearLayout>
</RelativeLayout>
视图保持器类:
class MyViewHolder extends RecyclerView.ViewHolder {
// Swipeable content container.
LinearLayout swipeableContent;
/*
... here goes other sub-views
*/
public ExpenseViewHolder(final View itemView) {
super(itemView);
// bind swipeable content container view
swipeableContent = (LinearLayout) itemView.findViewById(R.id.swipeable_content);
/*
... bind other sub-views
*/
}
}
itemTouchhelper.callback子类:
class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
@Override
public void onChildDraw(final Canvas c,
final RecyclerView recyclerView,
final RecyclerView.ViewHolder viewHolder,
final float dX,
final float dY,
final int actionState,
final boolean isCurrentlyActive) {
if (viewHolder instanceof MyViewHolder) {
// translate by swipe amount,
// the check symbol and the background will stay in place
((MyViewHolder) viewHolder).swipeableContent.setTranslationX(dX);
}
}
}