繁体   English   中英

单击时从查看器更新状态 android kotlin

[英]Update status from viewholder on click android kotlin

我有一个购物车(回收视图)。 当你点击一个产品时,它应该改变它的状态(改变背景背景和房间里的状态)我想这样解决这个问题:

当您单击产品时,更新 ROOM 中的产品状态并更新产品列表并根据状态更改颜色,但问题是在 itemadapter 中我无法调用 viewlifecycleowner。 它看不到它(如果我在片段中编写此逻辑,那么我无法从 ViewHolder 调用此 function。请帮助

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)
        })

    }
}

首先,而不是将视图 model 传递给适配器,您应该将 function (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) }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM