我看到这个问题问了几次,但也许是因为我使用的是骨肉皮库将项目添加到我的适配器,当其中一人被选中(类似于收音机,我不能够取消选择其他项目按钮功能)。我正在尝试将更改通知给适配器,并在某种程度上获得了所选项目的位置,但是我认为如果有人可以为我指出这一点,我可能仍然会缺少一些东西。
btn1.addEventListener('click', function(cls, event) {
btn1.className = cls;
}.bind(null, one_class));
这里是我的适配器,这样的想法是,当一个项目处于选定状态时,与之关联的imageView将是可见的,而其他所有项目都将变为不可见。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rvOptions.layoutManager = LinearLayoutManager(activity)
adapter = GroupAdapter()
rvOptions.adapter = adapter
viewModel = ViewModelProviders.of(activity as MainActivity).get(TestViewModel::class.java)
val myViewModel = ViewModelProvider(
this, MyViewModelFactoryForHashMap(arguments?.getString("headerText"))
).get(TestViewModel::class.java)
myViewModel.userMutableLiveData.observe(this, userListUpdateObserver)
}
private val userListUpdateObserver: Observer<Array<ModelTest>?> =
Observer { userArrayList ->
for (s in userArrayList!!) {
adapter.add(
RecyclerDialogOptionsItem(
activity as MainActivity,
s.title,
s.selected!!,
this@MyDialogFragment
)
)
}
}
override fun onClickItem( position: Int) {
adapter.notifyDataSetChanged()
}
}
非常感谢。
答案 0 :(得分:2)
第一个选项:创建适配器,并在适配器中创建局部变量,并检查所选位置为变量。
第二个选项: 在活动中创建名为selected_position的变量。 当函数onClickItem调用时,将更新此变量并通知适配器更改。 在您的项目中,检查活动中的变量,例如:
// Activity
selected_position = -1
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rvOptions.layoutManager = LinearLayoutManager(activity)
adapter = GroupAdapter()
rvOptions.adapter = adapter
viewModel = ViewModelProviders.of(activity as MainActivity).get(TestViewModel::class.java)
val myViewModel = ViewModelProvider(
this, MyViewModelFactoryForHashMap(arguments?.getString("headerText"))
).get(TestViewModel::class.java)
myViewModel.userMutableLiveData.observe(this, userListUpdateObserver)
}
private val userListUpdateObserver: Observer<Array<ModelTest>?> =
Observer { userArrayList ->
for (s in userArrayList!!) {
adapter.add(
RecyclerDialogOptionsItem(
activity as MainActivity,
s.title,
s.selected!!,
this@MyDialogFragment
)
)
}
}
override fun onClickItem( position: Int) {
selected_position = position
adapter.notifyDataSetChanged()
}
}
// Item
class RecyclerDialogOptionsItem(
private val activity: MainActivity,
private val title: String?,
private var selected: Boolean,
private val adapterListener: AdapterListener
) : Item<GroupieViewHolder>() {
companion object {
var clickListener: AdapterListener? = null
}
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.apply {
with(viewHolder.itemView) {
tvTitle.text = title
clickListener = adapterListener
if (activity.selected_position == position) {
ivChecked.visible()
} else {
ivChecked.invisible()
}
itemView.setOnClickListener {
clickListener?.onClickItem(adapterPosition)
}
}
}
}
override fun getLayout() = R.layout.rv_options_item_row
interface AdapterListener {
fun onClickItem(position: Int)
}
}