refactor(swipe): 迁移侧滑删除至 SwipeRecyclerView,移除 SwipeRevealLayout

- 新增 SwipeRecyclerView.aar 及使用说明文档
- 删除 SwipeRevealLayout.java / ViewBinderHelper.java
- DishListFragment、SamplingModeActivity、PrepareFoodActivity 改用 setSwipeMenuCreator API
- FoodListAdapter、DishPartAdapter 移除 ViewBinderHelper 侧滑状态管理代码
- 布局文件将 RecyclerView 替换为 SwipeRecyclerView,item 布局移除 SwipeRevealLayout 根节点
This commit is contained in:
2026-04-30 10:34:44 +08:00
parent 3842391555
commit dc55d3fde5
14 changed files with 643 additions and 1757 deletions
@@ -12,22 +12,13 @@ import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.view.swipereveallayout.ViewBinderHelper
class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
BaseQuickAdapter<CookFoodGoodsEntity, DishPartAdapter.VH>(list) {
var onDeleteClick: ((position: Int) -> Unit)? = null
/** item 主体点击回调 */
var onItemClick: ((position: Int) -> Unit)? = null
private val viewBinderHelper = ViewBinderHelper().apply {
setOpenOnlyOne(true)
}
fun closeAll() {
viewBinderHelper.closeAll()
}
inner class VH(var binding: ListItemDishCookBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
@@ -39,16 +30,7 @@ class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
override fun onBindViewHolder(holder: VH, position: Int, item: CookFoodGoodsEntity?) {
holder.binding.run {
val data = item ?: return
val itemId = data.goodsId ?: "${position}_${data.goodsName ?: ""}"
viewBinderHelper.bind(swipeRevealLayout, itemId)
// 暂时禁用侧滑能力,后续需要放开时改回 unlockSwipe + layoutDelete.visible()
viewBinderHelper.lockSwipe(itemId)
swipeRevealLayout.close(false)
layoutDelete.gone()
layoutDelete.setOnClickListener {
onDeleteClick?.invoke(holder.bindingAdapterPosition)
}
clBlock.setOnClickListener {
onItemClick?.invoke(holder.bindingAdapterPosition)
}
@@ -76,12 +58,10 @@ class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
if (data.isSetFinished) R.drawable.ic_dish_selected
else R.drawable.ic_dish_unselected
)
clBlock.run {
setBackgroundResource(
if (data.isItemClicked) R.drawable.shape_item_cook_dish
else R.drawable.shape_white_fb_15_corners
)
}
clBlock.setBackgroundResource(
if (data.isItemClicked) R.drawable.shape_item_cook_dish
else R.drawable.shape_white_fb_15_corners
)
}
}
}
}
@@ -9,7 +9,6 @@ import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemFoodListBinding
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.view.swipereveallayout.ViewBinderHelper
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.visible
import java.text.DecimalFormat
@@ -35,35 +34,16 @@ class FoodListAdapter(
SAMPLING_MODE
}
/** 删除按钮点击回调,由外部(Activity/Fragment)设置 */
var onDeleteClick: ((position: Int) -> Unit)? = null
/**
* item 主体点击回调,绑定在 mainViewclBlock)上,绕过 SwipeRevealLayout 的触摸拦截。
* 外部使用此回调替代 setOnDebouncedItemClick。
*/
/** item 主体点击回调 */
var onItemClick: ((position: Int) -> Unit)? = null
/**
* ViewBinderHelper 负责:
* - 同一时间只允许一个 item 展开(setOpenOnlyOne
* - RecyclerView 复用时恢复开合状态
*/
private val viewBinderHelper = ViewBinderHelper().apply {
setOpenOnlyOne(true)
}
/** 关闭所有已展开的侧滑 item,供外部在点击空白区域时调用 */
fun closeAll() {
viewBinderHelper.closeAll()
}
inner class VH(var binding: ListItemFoodListBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemFoodListBinding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
/**
* - 烹饪中:黑色文字、实线背景、显示"烹饪中"
* - 有累计重量:绿色文字、实线背景、显示累计统计
@@ -75,36 +55,12 @@ class FoodListAdapter(
val totalWeight = item.totalWeight ?: 0.0
val foodWeight = item.foodWeight ?: 0.0
// 用 foodId 作为唯一 key 恢复开合状态;不可滑动时锁定
val itemId = item.foodId ?: position.toString()
viewBinderHelper.bind(swipeRevealLayout, itemId)
if (isCooking) {
viewBinderHelper.unlockSwipe(itemId)
layoutDelete.visible()
} else {
viewBinderHelper.lockSwipe(itemId)
// 非烹饪中不允许侧滑,关闭可能的复用残留状态并隐藏删除按钮
swipeRevealLayout.close(false)
layoutDelete.gone()
}
// 绑定删除按钮回调
layoutDelete.setOnClickListener { onDeleteClick?.invoke(holder.bindingAdapterPosition) }
// 点击主内容区域:
// 1) 非烹饪中:先收起所有侧滑,再继续触发点击
// 2) 烹饪中:当前 item 若已展开则只收起,不触发点击
clBlock.setOnClickListener {
if (!isCooking) {
viewBinderHelper.closeAll()
onItemClick?.invoke(holder.bindingAdapterPosition)
} else if (!swipeRevealLayout.isClosed) {
viewBinderHelper.closeAll()
} else {
onItemClick?.invoke(holder.bindingAdapterPosition)
}
onItemClick?.invoke(holder.bindingAdapterPosition)
}
tvDishName.text = item.foodName
//烹饪中
// 烹饪中
if (isCooking) {
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.black))
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
@@ -113,7 +69,7 @@ class FoodListAdapter(
tvShowState.text = "烹饪中"
return@run
}
//非烹饪中,制作模式
// 非烹饪中,制作模式
if (mode == DisplayMode.COOKING_MODE) {
if (totalWeight > 0.0) {
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
@@ -129,7 +85,7 @@ class FoodListAdapter(
}
return@run
}
//非烹饪中,采样模式
// 非烹饪中,采样模式
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
@@ -36,6 +36,7 @@ import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.yanzhenjie.recyclerview.SwipeMenuItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -359,22 +360,6 @@ class PrepareFoodActivity : BaseActivity() {
}
notifyDataSetChanged()
}
onDeleteClick = onDeleteClick@{ positon ->
Log.d(TAG, "onFoodItemClick: ${list[positon].toJsonString()}")
if (list[positon].isNewDishType.not()) {
toast("只能删除刚添加的食材")
return@onDeleteClick
}
CommonDialog(this@PrepareFoodActivity)
.setTitle("删除确认")
.setContent("确定删除食材「${list[positon].goodsName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
adapter.removeAt(positon)
toast("已删除")
}
.show()
}
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, positon ->
Log.d(TAG, "onFoodItemClick: ${list[positon].toJsonString()}")
if (list[positon].isOriginalData) {
@@ -398,21 +383,52 @@ class PrepareFoodActivity : BaseActivity() {
binding.rvDishPartList.run {
layoutManager =
LinearLayoutManager(this@PrepareFoodActivity, LinearLayoutManager.VERTICAL, false)
adapter = dishPartAdapter
addOnItemTouchListener(object : androidx.recyclerview.widget.RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(
rv: androidx.recyclerview.widget.RecyclerView,
e: android.view.MotionEvent
): Boolean {
if (e.action == android.view.MotionEvent.ACTION_DOWN) {
dishPartAdapter.closeAll()
}
return false
// 仅 isNewDishType=true 的 item 显示侧滑删除菜单(必须在 setAdapter 之前调用)
setSwipeMenuCreator { _, rightMenu, position ->
if (list.getOrNull(position)?.isNewDishType == true) {
rightMenu.addMenuItem(buildDeleteMenuItem())
}
})
}
// 点击侧滑菜单项:先关闭菜单,再弹窗确认删除
setOnItemMenuClickListener { menuBridge, position ->
menuBridge.closeMenu()
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
CommonDialog(this@PrepareFoodActivity)
.setTitle("删除确认")
.setContent("确定删除食材「${item.goodsName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
dishPartAdapter.removeAt(position)
toast("已删除")
}.show()
}
// item 点击事件
setOnItemClickListener { _, position ->
dishPartAdapter.onItemClick?.invoke(position)
}
adapter = dishPartAdapter
}
}
/**
* 构建侧滑删除菜单项
*/
private fun buildDeleteMenuItem(): SwipeMenuItem {
return SwipeMenuItem(this).apply {
setImage(R.drawable.ic_trash_white)
setBackground(R.drawable.bg_swipe_delete)
width = dp2px(160)
height = ViewGroup.LayoutParams.MATCH_PARENT
}
}
/**
* dp 转 px
*/
private fun dp2px(dp: Int): Int {
return (dp * resources.displayMetrics.density + 0.5f).toInt()
}
override fun onResume() {
super.onResume()
pageVisible = true
@@ -4,7 +4,7 @@ import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
@@ -18,14 +18,15 @@ import com.shuwei.dish.match.databinding.ActivitySamplingModeBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.dialog.CommonDialog
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.net.UiState
import com.shuwei.dish.match.utils.DateTimeUtil
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.yanzhenjie.recyclerview.SwipeMenuItem
import java.io.Serializable
import kotlinx.coroutines.launch
import com.shuwei.dish.match.net.UiState
/**
* 采样模式
*/
@@ -161,23 +162,6 @@ class SamplingModeActivity : BaseActivity() {
private val dishAdapter by lazy {
FoodListAdapter(list = list, mode = FoodListAdapter.DisplayMode.SAMPLING_MODE).apply {
isStateViewEnable = true
onDeleteClick = { position ->
CommonDialog(this@SamplingModeActivity)
.setTitle("删除确认")
.setContent("确定要删除「${list[position].foodName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
deleteCookFoodAndGoods(foodId = list[position].foodId ?: "") {
if (list.size > 1) {
removeAt(position)
} else {
loadEmptyView()
}
toast("已删除")
}
}
.show()
}
onItemClick = { position ->
judgeDeviceConfig {
onItemClick(position)
@@ -207,19 +191,58 @@ class SamplingModeActivity : BaseActivity() {
binding.rvSamplingList.run {
layoutManager =
LinearLayoutManager(this@SamplingModeActivity, LinearLayoutManager.VERTICAL, false)
adapter = dishAdapter
// 点击列表空白区域时关闭已展开的侧滑 item
addOnItemTouchListener(object : androidx.recyclerview.widget.RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(rv: androidx.recyclerview.widget.RecyclerView, e: MotionEvent): Boolean {
if (e.action == MotionEvent.ACTION_DOWN) {
dishAdapter.closeAll()
}
return false
// 根据 isCooking 决定是否显示侧滑删除菜单(必须在 setAdapter 之前调用)
setSwipeMenuCreator { _, rightMenu, position ->
if (list.getOrNull(position)?.isCooking == true) {
rightMenu.addMenuItem(buildDeleteMenuItem())
}
})
}
// 点击侧滑菜单项:先关闭菜单,再弹窗确认删除
setOnItemMenuClickListener { menuBridge, position ->
menuBridge.closeMenu()
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
CommonDialog(this@SamplingModeActivity)
.setTitle("删除确认")
.setContent("确定要删除「${item.foodName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
deleteCookFoodAndGoods(foodId = item.foodId ?: "") {
if (list.size > 1) {
dishAdapter.removeAt(position)
} else {
loadEmptyView()
}
toast("已删除")
}
}.show()
}
// item 点击事件
setOnItemClickListener { _, position ->
judgeDeviceConfig { onItemClick(position) }
}
adapter = dishAdapter
}
}
/**
* 构建侧滑删除菜单项
*/
private fun buildDeleteMenuItem(): SwipeMenuItem {
return SwipeMenuItem(this).apply {
setImage(R.drawable.ic_trash_white)
setBackground(R.drawable.bg_swipe_delete)
width = dp2px(160)
height = ViewGroup.LayoutParams.MATCH_PARENT
}
}
/**
* dp 转 px
*/
private fun dp2px(dp: Int): Int {
return (dp * resources.displayMetrics.density + 0.5f).toInt()
}
@SuppressLint("ClickableViewAccessibility")
private fun addViewListener() {
binding.btnAddSampling.setOnClickListener {
@@ -1,28 +1,30 @@
package com.shuwei.dish.match.ui.fragment
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.FoodListAdapter
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.base.BaseFragment
import com.shuwei.dish.match.databinding.FragmentDishListBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.dialog.CommonDialog
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.dialog.CommonDialog
import com.shuwei.dish.match.net.UiState
import com.shuwei.dish.match.ui.PrepareFoodActivity
import com.shuwei.dish.match.ui.CookingModeActivity
import com.shuwei.dish.match.ui.PrepareFoodActivity
import com.shuwei.dish.match.ui.SubmitFoodActivity
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toast
import com.yanzhenjie.recyclerview.SwipeMenuItem
import java.io.Serializable
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
@@ -53,20 +55,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
private val dishAdapter by lazy {
FoodListAdapter(list = list).apply {
isStateViewEnable = true
onDeleteClick = { position ->
CommonDialog(activity)
.setTitle("删除确认")
.setContent("确定要删除「${list[position].foodName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
activity.deleteCookFoodAndGoods(foodId = list[position].foodId ?: "") {
activity.toast("已删除")
pageNo = 1
getDishList()
}
}
.show()
}
onItemClick = { position ->
if (isAdded && isVisible) {
activity.judgeDeviceConfig {
@@ -80,21 +68,15 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
private fun onItemClick(position: Int) {
val item = list[position]
if (item.isCooking) {
//烹饪中,跳到称熟重页面
// 烹饪中,跳到称熟重页面
activity.startActivity<SubmitFoodActivity> {
putExtra(
SubmitFoodActivity.FOOD_ITEM,
item as Serializable
)
putExtra(SubmitFoodActivity.FOOD_ITEM, item as Serializable)
}
return
}
item.dinnerType = dinnerType
activity.startActivity<PrepareFoodActivity> {
putExtra(
SubmitFoodActivity.FOOD_ITEM,
item as Serializable
)
putExtra(SubmitFoodActivity.FOOD_ITEM, item as Serializable)
}
}
@@ -109,18 +91,37 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
activity = requireActivity() as CookingModeActivity
dinnerType = arguments?.getString(DINNER_TYPE, "0") ?: "0"
binding.rvDishList.run {
layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
adapter = dishAdapter
// 点击列表空白区域时关闭已展开的侧滑 item
addOnItemTouchListener(object : androidx.recyclerview.widget.RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(rv: androidx.recyclerview.widget.RecyclerView, e: MotionEvent): Boolean {
if (e.action == MotionEvent.ACTION_DOWN) {
dishAdapter.closeAll()
}
return false
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
// 侧滑菜单:仅烹饪中的 item 显示删除按钮(必须在 setAdapter 之前调用)
setSwipeMenuCreator { _, rightMenu, position ->
if (list.getOrNull(position)?.isCooking == true) {
rightMenu.addMenuItem(buildDeleteMenuItem(requireContext()))
}
})
}
// 菜单点击:先关闭菜单,再弹确认弹窗
setOnItemMenuClickListener { menuBridge, position ->
menuBridge.closeMenu()
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
CommonDialog(activity)
.setTitle("删除确认")
.setContent("确定要删除「${item.foodName}」吗?")
.setNegativeButton("取消")
.setPositiveButton("删除") {
activity.deleteCookFoodAndGoods(foodId = item.foodId ?: "") {
activity.toast("已删除")
pageNo = 1
getDishList()
}
}
.show()
}
// item 点击
setOnItemClickListener { _, position ->
if (isAdded && isVisible) {
activity.judgeDeviceConfig { onItemClick(position) }
}
}
adapter = dishAdapter
}
addViewListener()
initObserver()
@@ -131,6 +132,22 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
binding.refreshLayout.setEnableRefresh(true)
}
/**
* 构建统一样式的删除菜单项
*/
private fun buildDeleteMenuItem(context: Context): SwipeMenuItem {
return SwipeMenuItem(context).apply {
setImage(R.drawable.ic_trash_white)
setBackground(R.drawable.bg_swipe_delete)
width = dp2px(context, 160)
height = ViewGroup.LayoutParams.MATCH_PARENT
}
}
private fun dp2px(context: Context, dp: Int): Int {
return (dp * context.resources.displayMetrics.density + 0.5f).toInt()
}
/**
* 用 combine 同时监听网络结果与本地数据,网络成功时统一合并渲染
* pageNo > 1(加载更多)时 cookFoodListState 不参与合并,直接追加网络数据
@@ -156,7 +173,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
finishRefresh()
activity.delayDismissLoading()
if (pageNo == 1) {
// 网络异常或接口不通时,降级使用本地数据;本地也为空才显示空视图
if (localList.isNullOrEmpty()) {
loadEmptyView()
} else {
@@ -209,7 +225,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
"placeId" to BaseApp.canteenId,
"dinnerType" to getDinnerTypeText()
)
// 网络与本地并行触发,pageNo > 1 时不重复查询本地数据
activity.getFoodList(param = param)
if (pageNo == 1) activity.getCookFoodList()
}
@@ -233,7 +248,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
emptyViewBinding!!.tvContent.text = "暂无数据"
emptyViewBinding!!.tvSubContent.text = "获取菜品数据失败,请检查网络设置或稍后重试"
dishAdapter.stateView = emptyViewBinding!!.root
//dishAdapter.setStateViewLayout(requireContext(), R.layout-sw800dp.layout_empty_view)
} catch (e: Exception) {
e.printStackTrace()
}
@@ -249,7 +263,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
/**
* 将网络数据与本地烹饪中数据合并后渲染列表
* pageNo > 1 时忽略本地数据,直接追加网络数据,避免 combine 带入旧的本地状态
*/
@SuppressLint("NotifyDataSetChanged")
private fun loadAndMergeDishList(
@@ -258,7 +271,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
) {
try {
if (isAdded.not()) return
// pageNo > 1 时不参与本地合并,避免 combine 带入旧的本地状态
val effectiveLocalList = if (pageNo == 1) localList else null
if (records.isNullOrEmpty() && effectiveLocalList.isNullOrEmpty()) {
if (pageNo == 1) loadEmptyView()
@@ -268,7 +280,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
val mergedList = records?.toMutableList() ?: mutableListOf()
// 仅 pageNo == 1 时才有本地数据参与合并
if (!effectiveLocalList.isNullOrEmpty()) {
val cookingItems = mutableListOf<FoodRecord>()
effectiveLocalList.forEachIndexed { index, entity ->
@@ -280,7 +291,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
food.dinnerType = entity.dinnerType ?: "0"
cookingItems.add(food)
} else {
// 当前网络数据不包含该本地记录,直接构造
cookingItems.add(
FoodRecord(
foodId = entity.foodId,
@@ -296,7 +306,6 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
}
if (pageNo >= 2 && !localList.isNullOrEmpty()) {
//第2页起,从mergedList中移除localList中的同foodId数据
val localIds = localList.map { it.foodId }.toHashSet()
mergedList.removeAll { it.foodId in localIds }
}
@@ -310,5 +319,4 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
e.printStackTrace()
}
}
}
}
@@ -1,271 +0,0 @@
/**
The MIT License (MIT)
Copyright (c) 2016 Chau Thai
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.shuwei.dish.match.view.swipereveallayout;
import android.os.Bundle;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* ViewBinderHelper provides a quick and easy solution to restore the open/close state
* of the items in RecyclerView, ListView, GridView or any view that requires its child view
* to bind the view to a data object.
*
* <p>When you bind you data object to a view, use {@link #bind(SwipeRevealLayout, String)} to
* save and restore the open/close state of the view.</p>
*
* <p>Optionally, if you also want to save and restore the open/close state when the device's
* orientation is changed, call {@link #saveStates(Bundle)} in {@link android.app.Activity#onSaveInstanceState(Bundle)}
* and {@link #restoreStates(Bundle)} in {@link android.app.Activity#onRestoreInstanceState(Bundle)}</p>
*/
public class ViewBinderHelper {
private static final String BUNDLE_MAP_KEY = "ViewBinderHelper_Bundle_Map_Key";
private Map<String, Integer> mapStates = Collections.synchronizedMap(new HashMap<String, Integer>());
private Map<String, SwipeRevealLayout> mapLayouts = Collections.synchronizedMap(new HashMap<String, SwipeRevealLayout>());
private Set<String> lockedSwipeSet = Collections.synchronizedSet(new HashSet<String>());
private volatile boolean openOnlyOne = false;
private final Object stateChangeLock = new Object();
/**
* Help to save and restore open/close state of the swipeLayout. Call this method
* when you bind your view holder with the data object.
*
* @param swipeLayout swipeLayout of the current view.
* @param id a string that uniquely defines the data object of the current view.
*/
public void bind(final SwipeRevealLayout swipeLayout, final String id) {
if (swipeLayout.shouldRequestLayout()) {
swipeLayout.requestLayout();
}
mapLayouts.values().remove(swipeLayout);
mapLayouts.put(id, swipeLayout);
swipeLayout.abort();
swipeLayout.setDragStateChangeListener(new SwipeRevealLayout.DragStateChangeListener() {
@Override
public void onDragStateChanged(int state) {
mapStates.put(id, state);
if (openOnlyOne) {
closeOthers(id, swipeLayout);
}
}
});
// first time binding.
if (!mapStates.containsKey(id)) {
mapStates.put(id, SwipeRevealLayout.STATE_CLOSE);
swipeLayout.close(false);
}
// not the first time, then close or open depends on the current state.
else {
int state = mapStates.get(id);
if (state == SwipeRevealLayout.STATE_CLOSE || state == SwipeRevealLayout.STATE_CLOSING ||
state == SwipeRevealLayout.STATE_DRAGGING) {
swipeLayout.close(false);
} else {
swipeLayout.open(false);
}
}
// set lock swipe
swipeLayout.setLockDrag(lockedSwipeSet.contains(id));
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {@link android.app.Activity#onSaveInstanceState(Bundle)}
*/
public void saveStates(Bundle outState) {
if (outState == null)
return;
Bundle statesBundle = new Bundle();
for (Map.Entry<String, Integer> entry : mapStates.entrySet()) {
statesBundle.putInt(entry.getKey(), entry.getValue());
}
outState.putBundle(BUNDLE_MAP_KEY, statesBundle);
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {@link android.app.Activity#onRestoreInstanceState(Bundle)}
*/
@SuppressWarnings({"unchecked", "ConstantConditions"})
public void restoreStates(Bundle inState) {
if (inState == null)
return;
if (inState.containsKey(BUNDLE_MAP_KEY)) {
HashMap<String, Integer> restoredMap = new HashMap<>();
Bundle statesBundle = inState.getBundle(BUNDLE_MAP_KEY);
Set<String> keySet = statesBundle.keySet();
if (keySet != null) {
for (String key : keySet) {
restoredMap.put(key, statesBundle.getInt(key));
}
}
mapStates = restoredMap;
}
}
/**
* Lock swipe for some layouts.
* @param id a string that uniquely defines the data object.
*/
public void lockSwipe(String... id) {
setLockSwipe(true, id);
}
/**
* Unlock swipe for some layouts.
* @param id a string that uniquely defines the data object.
*/
public void unlockSwipe(String... id) {
setLockSwipe(false, id);
}
/**
* @param openOnlyOne If set to true, then only one row can be opened at a time.
*/
public void setOpenOnlyOne(boolean openOnlyOne) {
this.openOnlyOne = openOnlyOne;
}
/**
* Open a specific layout.
* @param id unique id which identifies the data object which is bind to the layout.
*/
public void openLayout(final String id) {
synchronized (stateChangeLock) {
mapStates.put(id, SwipeRevealLayout.STATE_OPEN);
if (mapLayouts.containsKey(id)) {
final SwipeRevealLayout layout = mapLayouts.get(id);
layout.open(true);
}
else if (openOnlyOne) {
closeOthers(id, mapLayouts.get(id));
}
}
}
/**
* Close a specific layout.
* @param id unique id which identifies the data object which is bind to the layout.
*/
public void closeLayout(final String id) {
synchronized (stateChangeLock) {
mapStates.put(id, SwipeRevealLayout.STATE_CLOSE);
if (mapLayouts.containsKey(id)) {
final SwipeRevealLayout layout = mapLayouts.get(id);
layout.close(true);
}
}
}
/**
* 关闭所有已展开的侧滑布局,用于点击空白区域时收起侧滑。
*/
public void closeAll() {
synchronized (stateChangeLock) {
for (Map.Entry<String, Integer> entry : mapStates.entrySet()) {
entry.setValue(SwipeRevealLayout.STATE_CLOSE);
}
for (SwipeRevealLayout layout : mapLayouts.values()) {
layout.close(true);
}
}
}
/**
* Close others swipe layout.
* @param id layout which bind with this data object id will be excluded.
* @param swipeLayout will be excluded.
*/
private void closeOthers(String id, SwipeRevealLayout swipeLayout) {
synchronized (stateChangeLock) {
// close other rows if openOnlyOne is true.
if (getOpenCount() > 1) {
for (Map.Entry<String, Integer> entry : mapStates.entrySet()) {
if (!entry.getKey().equals(id)) {
entry.setValue(SwipeRevealLayout.STATE_CLOSE);
}
}
for (SwipeRevealLayout layout : mapLayouts.values()) {
if (layout != swipeLayout) {
layout.close(true);
}
}
}
}
}
private void setLockSwipe(boolean lock, String... id) {
if (id == null || id.length == 0)
return;
if (lock)
lockedSwipeSet.addAll(Arrays.asList(id));
else
lockedSwipeSet.removeAll(Arrays.asList(id));
for (String s : id) {
SwipeRevealLayout layout = mapLayouts.get(s);
if (layout != null) {
layout.setLockDrag(lock);
}
}
}
private int getOpenCount() {
int total = 0;
for (int state : mapStates.values()) {
if (state == SwipeRevealLayout.STATE_OPEN || state == SwipeRevealLayout.STATE_OPENING) {
total++;
}
}
return total;
}
}
@@ -92,15 +92,15 @@
</FrameLayout>
<androidx.recyclerview.widget.RecyclerView
<com.yanzhenjie.recyclerview.SwipeRecyclerView
android:id="@+id/rvDishPartList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:overScrollMode="never"
android:scrollbars="vertical"
tools:itemCount="3"
tools:listitem="@layout/list_item_dish_cook"
android:scrollbars="vertical" />
tools:listitem="@layout/list_item_dish_cook" />
</LinearLayout>
@@ -76,7 +76,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
<com.yanzhenjie.recyclerview.SwipeRecyclerView
android:id="@+id/rvSamplingList"
android:layout_width="match_parent"
android:layout_height="match_parent"
@@ -26,7 +26,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
<com.yanzhenjie.recyclerview.SwipeRecyclerView
android:id="@+id/rvDishList"
android:layout_width="match_parent"
android:layout_height="match_parent"
+72 -95
View File
@@ -1,109 +1,86 @@
<?xml version="1.0" encoding="utf-8"?>
<com.shuwei.dish.match.view.swipereveallayout.SwipeRevealLayout xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipeRevealLayout"
android:id="@+id/clBlock"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="15dp"
app:dragEdge="right">
android:background="@drawable/shape_white_fb_15_corners">
<FrameLayout
android:id="@+id/layoutDelete"
android:layout_width="160dp"
android:layout_height="120dp"
android:background="@drawable/bg_swipe_delete">
<TextView
android:id="@+id/tvDishName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:ellipsize="end"
android:includeFontPadding="false"
android:maxLines="1"
android:textColor="@color/black"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvDishType"
app:layout_constraintEnd_toStartOf="@+id/tvDishWeight"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed"
tools:text="雪菜" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:contentDescription="删除"
android:src="@drawable/ic_trash_white" />
<TextView
android:id="@+id/tvDishType"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:ellipsize="end"
android:includeFontPadding="false"
android:maxLines="1"
android:textColor="@color/black999"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/tvDishName"
app:layout_constraintStart_toStartOf="@id/tvDishName"
app:layout_constraintTop_toBottomOf="@id/tvDishName"
tools:text="主辅材:主材" />
</FrameLayout>
<ImageView
android:id="@+id/ivOperateIcon"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/ivClearIcon"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription"
tools:src="@drawable/ic_dish_selected" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/clBlock"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="@drawable/shape_white_fb_15_corners">
<ImageView
android:id="@+id/ivClearIcon"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_marginEnd="10dp"
android:src="@drawable/ic_delete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="@+id/tvDishName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:ellipsize="end"
android:includeFontPadding="false"
android:maxLines="1"
android:textColor="@color/black"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvDishType"
app:layout_constraintEnd_toStartOf="@+id/tvDishWeight"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed"
tools:text="雪菜" />
<TextView
android:id="@+id/tvDishWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:hint="-"
android:textColor="@color/dish_green"
android:textColorHint="@color/gray_d6"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@id/ivOperateIcon"
app:layout_constraintEnd_toStartOf="@id/ivOperateIcon"
app:layout_constraintTop_toTopOf="@id/ivOperateIcon"
tools:ignore="HardcodedText"
tools:text="375克" />
<TextView
android:id="@+id/tvDishType"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:ellipsize="end"
android:includeFontPadding="false"
android:maxLines="1"
android:textColor="@color/black999"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/tvDishName"
app:layout_constraintStart_toStartOf="@id/tvDishName"
app:layout_constraintTop_toBottomOf="@id/tvDishName"
tools:text="主辅材:主材" />
<ImageView
android:id="@+id/ivOperateIcon"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/ivClearIcon"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription"
tools:src="@drawable/ic_dish_selected" />
<ImageView
android:id="@+id/ivClearIcon"
android:layout_width="80dp"
android:layout_height="60dp"
android:layout_marginEnd="10dp"
android:src="@drawable/ic_delete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="@+id/tvDishWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:hint="-"
android:textColor="@color/dish_green"
android:textColorHint="@color/gray_d6"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="@id/ivOperateIcon"
app:layout_constraintEnd_toStartOf="@id/ivOperateIcon"
app:layout_constraintTop_toTopOf="@id/ivOperateIcon"
tools:ignore="HardcodedText"
tools:text="375克" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.shuwei.dish.match.view.swipereveallayout.SwipeRevealLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
+49 -75
View File
@@ -1,87 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<com.shuwei.dish.match.view.swipereveallayout.SwipeRevealLayout
xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipeRevealLayout"
android:id="@+id/clBlock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="150dp"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="8dp"
app:dragEdge="right">
android:background="@drawable/shape_white_fb_15_corners"
android:foreground="?android:attr/selectableItemBackground"
android:paddingStart="30dp"
android:paddingEnd="30dp">
<!-- 后景层(secondaryView = getChildAt(0)):删除按钮,右对齐 -->
<FrameLayout
android:id="@+id/layoutDelete"
android:layout_width="160dp"
android:layout_height="150dp"
android:background="@drawable/bg_swipe_delete">
<TextView
android:id="@+id/tvShowState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black999"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="烹饪中" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:contentDescription="删除"
android:src="@drawable/ic_trash_white" />
<TextView
android:id="@+id/tvDishName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/dish_green"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvDishCount"
app:layout_constraintEnd_toStartOf="@id/tvShowState"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed"
tools:text="冬虫夏草炝拌芥兰苗" />
</FrameLayout>
<TextView
android:id="@+id/tvDishCount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/black999"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/tvDishName"
app:layout_constraintStart_toStartOf="@id/tvDishName"
app:layout_constraintTop_toBottomOf="@id/tvDishName"
tools:text="累计统计:2.3kg(2次)" />
<!-- 前景层(mainView = getChildAt(1)):item 主内容 -->
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/clBlock"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="@drawable/shape_white_fb_15_corners"
android:foreground="?android:attr/selectableItemBackground"
android:paddingStart="30dp"
android:paddingEnd="30dp">
<TextView
android:id="@+id/tvShowState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black999"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="烹饪中" />
<TextView
android:id="@+id/tvDishName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/dish_green"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvDishCount"
app:layout_constraintEnd_toStartOf="@id/tvShowState"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed"
tools:text="冬虫夏草炝拌芥兰苗" />
<TextView
android:id="@+id/tvDishCount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/black999"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/tvDishName"
app:layout_constraintStart_toStartOf="@id/tvDishName"
app:layout_constraintTop_toBottomOf="@id/tvDishName"
tools:text="累计统计:2.3kg(2次)" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.shuwei.dish.match.view.swipereveallayout.SwipeRevealLayout>
</androidx.constraintlayout.widget.ConstraintLayout>