android - 点击 android kotlin 从查看器更新状态
问题描述
我有一个购物车(回收视图)。当你点击一个产品时,它应该改变它的状态(改变背景背景和房间里的状态)我想这样解决这个问题:
当您单击产品时,更新 ROOM 中的产品状态并更新产品列表并根据状态更改颜色,但问题是在 itemadapter 中我无法调用 viewlifecycleowner。它看不到它(如果我在片段中编写此逻辑,则无法从 ViewHolder 调用此函数。请帮助
class OrderItemAdapter() : RecyclerView.Adapter<OrderItemAdapter.ViewHolder>() {
private var mListProduct: MutableList<Product?>? = null
private var mViewModel: OrderViewModel? = null
constructor(viewModel: OrderViewModel, listProduct: MutableList<Product?>?) : this() {
mListProduct = listProduct
mViewModel = viewModel
}
override fun getItemCount(): Int {
return if (mListProduct == null) 0 else mListProduct!!.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.frg_order_item, parent, false))
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
private val title: TextView = view.findViewById(R.id.product_name)
private val count: TextView = view.findViewById(R.id.product_count)
private val price: TextView = view.findViewById(R.id.product_price)
private val btnEdit: Button = view.findViewById(R.id.product_edit)
private val btnChange: Button = view.findViewById(R.id.button_change)
private val productImage: ImageView = view.findViewById(R.id.product_image)
private val btnDone: Button = view.findViewById(R.id.done)
@ExperimentalCoroutinesApi
fun bind(pos: Int) {
title.text = mListProduct?.get(pos)?.name
price.text = mListProduct?.get(pos)?.price.toString()
count.text = mListProduct?.get(pos)?.brgew.toString() + " " + mListProduct?.get(pos)?.gewei.toString() + " " + mListProduct?.get(pos)?.quantity.toString() + " " + mListProduct?.get(pos)?.units.toString()
view.setBackgroundColor(changerColorStatus( mListProduct?.get(pos)?.status!!))
//count.text = pos.toString()
productImage.downloadAndSetImage(mListProduct?.get(pos)?.pathImage!!)
btnDone.setOnClickListener {
val product = mListProduct?.get(pos)
if (product != null) {
mViewModel!!.toCollectProduct(product.id!!)
}
}
btnEdit.setOnClickListener {
val product = mListProduct?.get(pos)
if (product != null) {
view.findNavController().navigate(
OrderFragmentDirections.actionOrderFragmentToProductEntryDialogFragment(product)
}
}
btnChange.setOnClickListener {
val product = mListProduct?.get(pos)
view.findNavController().navigate((OrderFragmentDirections.actionOrderFragmentToBarcodeScanningActivity()))
}
}
}
fun submitList(it: List<Product>?) {
mListProduct = it?.toMutableList()
notifyDataSetChanged()
}
fun changerColorStatus(statusProduct: StatusProduct): Int {
return when (statusProduct) {
StatusProduct.COLLECTED -> Color.GREEN
StatusProduct.NOT_COLLECTED -> Color.YELLOW
StatusProduct.EDIT -> Color.CYAN
StatusProduct.REMOVED -> Color.GRAY
StatusProduct.REPLACE -> Color.GRAY
}
}
}
订单视图模型
@ExperimentalCoroutinesApi
class OrderViewModel @ViewModelInject constructor(private val ordersRepository: OrdersRepository) :
ViewModel() {
//TODO MAKE MUTABLE
fun getBasket(id: Long): LiveData<Resource<List<Product>>> = ordersRepository.getBasket(id)
fun toCollectProduct(id: Long) {
ordersRepository.toCollectProduct(id)
}
fun updateFromLocalDB(id: Long) = ordersRepository.getOrderLocal(id);
}
订单片段
@ExperimentalCoroutinesApi
@AndroidEntryPoint
class OrderFragment : Fragment() {
private var orderId = -1L
private val mViewModel: OrderViewModel by viewModels()
private lateinit var mAdapter: OrderItemAdapter
private lateinit var recycler: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.frg_order, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = view.chat_recycle_view
arguments?.let {
val safeArgs = OrderFragmentArgs.fromBundle(it)
orderId = safeArgs.idOrder
//TODO Log it
setupRecycler()
setupObservers()
}
fab.setOnClickListener {
view.findNavController().navigate(R.id.action_orderFragment_to_barcodeScanningActivity)
}
}
private fun setupRecycler() {
recycler.layoutManager = LinearLayoutManager(context)
val itemDecor = DividerItemDecoration(context, RecyclerView.VERTICAL)
recycler.addItemDecoration(itemDecor)
mAdapter = OrderItemAdapter(mViewModel, null)
recycler.adapter = mAdapter
chat_swipe_refresh.setOnRefreshListener { setupObservers() }
// mViewModel.getBasket(orderId)
}
private fun setupObservers() {
mViewModel.getBasket(orderId).observe(viewLifecycleOwner, Observer {
when (it.status) {
Resource.Status.SUCCESS -> {
//binding.progressBar.visibility = View.GONE
isRefreshing(false)
if (!it.data?.isNullOrEmpty()!!) mAdapter.submitList(it.data)
}
Resource.Status.ERROR -> {
Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show()
isRefreshing(false)
}
Resource.Status.LOADING -> {
isRefreshing(true)
//progressBar.visibility = View.VISIBLE
}
}
})
}
private fun isRefreshing(refreshing : Boolean){
chat_swipe_refresh.isRefreshing = refreshing
}
fun updateFromLocalDB(id: Long,view: View){
mViewModel!!.updateFromLocalDB(id).observe(viewLifecycleOwner, Observer {
mAdapter.submitList(it)
})
}
}
解决方案
首先,而不是将视图模型传递给适配器,您应该将函数(lambda 或侦听器)传递给您的适配器,然后是您的 viewHolder,例如:
class Yourfragment {
val adapter = YourAdapter( { it:Int ->
// here you can use viewModel calls
})
}
class YourAdapter(val clickFunc:(Int) -> Unit){
// ...
}
// (Int)->Unit mean clickFunc is a function which gets integer as argument and return Unit
// then in your viewHolder.
init {
itemView.setOnCLickListener{ clickFunc.invoke(adapterPosition) }
}
推荐阅读
- python - 从 gensim.models.keyedvectors.Word2VecKeyedVectors 类型的模型传递到 gensim.models.word2vec.Word2Vec 类型的模型
- javascript - 如何让线条在 d3.js 多折线图上呈现?
- python - 如何使用其他列和字符串格式在熊猫数据框中生成列
- sum - 图表。在堆积条形图中显示值的总和
- sql - 如何在 sql 查询的输出上添加过滤器以获得布尔值的答案?
- macos - 当我添加 UserName 属性时,launchctl exit 78(如何以不同的用户身份运行守护进程?)
- javascript - 将 Javascript 的 if...elseif 语句与 Firebase 链接
- firebase - 是否可以为 B2B 客户使用 Firebase 云消息传递来接触最终用户?
- python - 使用列表生成 url
- javascript - 绘制时不出现传单 divIcon