我有一个适配器,该适配器具有一个用于处理数据绑定的视图保持器。如果数组为空,我希望能够将用户重定向到其他页面(将片段转换为错误片段)。
这是我的适配器:
$Word1 = "This";
$Word2 = "is";
$Word3 = "Test";
print "$Word1 $Word2 $Word3\n";
这是我称为适配器的片段:
class UserCardsRecyclerViewAdapter(val listener: (Card) -> Unit) : RecyclerView.Adapter<UserCardsRecyclerViewAdapter.ViewHolder>() {
private var cardsList = mutableListOf<Card>()
private var views = mutableListOf<ViewHolder>()
fun addItems(items: List<Card>){
cardsList.addAll(items)
notifyDataSetChanged()
}
fun clear(){
cardsList = mutableListOf()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.item_user_card, parent, false)
return ViewHolder(view).also { views.add(it) }
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val card = cardsList[position]
holder.bind(card, listener)
}
override fun getItemCount() = cardsList.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(card: Card, listener: (Card) -> Unit) {
if(card.name.isEmpty()){
Toast.makeText(itemView.context,"Empty",Toast.LENGTH_LONG).show()
}
itemView.card_name.text = card.name
itemView.card_number.text = card.number.toString()
card.expiration?.let {
itemView.valid_title.visibility =View.VISIBLE
itemView.valid_date.visibility = View.VISIBLE
itemView.valid_date.text = it.ParseMonthYear()
}
GlideApp.with(itemView.context).load(card.mosaicImageUrl)
.fitCenter()
.apply(RequestOptions.bitmapTransform(
RoundedCornersTransformation(50, 0, RoundedCornersTransformation.CornerType.ALL)))
.into(itemView.card_image)
itemView.setOnClickListener { listener(card) }
}
}
}
这是我的viewModel,其中包含与存储库和API通信的方法
override fun doOnCreated() {
initCardsRecyclerView()
viewModel.loadCards()
}
private fun initCardsRecyclerView(){
dataBinding.rvCards.setHasFixedSize(true)
dataBinding.rvCards.setItemViewCacheSize(1)
dataBinding.rvCards.isNestedScrollingEnabled = false
dataBinding.rvCards.layoutManager = LinearLayoutManager(context)
userCardsRecyclerViewAdapter = UserCardsRecyclerViewAdapter(::handleCardClickListener)
dataBinding.rvCards.adapter = userCardsRecyclerViewAdapter
viewModel.retrieveCards().observe(this, Observer<List<Card>> {
userCardsRecyclerViewAdapter.apply {
clear()
addItems(it)
}
})
}
这是我的存储库
class CardsViewModel @Inject constructor(
private val cardsRepository: CardsRepository
) : ViewModel() {
private val loading = MutableLiveData<Boolean>()
private val cards = MutableLiveData<List<Card>>()
fun retrieveCards(): LiveData<List<Card>> = cards
fun retrieveLoading(): LiveData<Boolean> = loading
fun loadCards(){
loading.postValue(true)
cardsRepository.getUserCards(
{
cards.postValue(it)
loading.postValue(false)
},
{
loading.postValue(false)
})
}
}