How can i get item position of item selected with checkBox in RecyclerView ? here you can see how it looks like
TaskRecyclerAdapter.kt
class TaskRecycleAdapter: RecyclerView.Adapter<TaskRecycleAdapter.MyViewHolder>() {
private var list = emptyList<Data>()
private lateinit var mListener : OnItemClickListener
class MyViewHolder(binding: TaskHolderBinding, listener: OnItemClickListener): RecyclerView.ViewHolder(binding.root) {
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: OnItemClickListener) {
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(TaskHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false), mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = list[position]
holder.itemView.findViewById<TextView>(R.id.task).text = item.task
holder.itemView.findViewById<TextView>(R.id.taskDescription).text = item.task_Details
}
override fun getItemCount(): Int {
return list.size
}
fun setData(newList: List<Data>) {
val diffUtil = DiffUtil(list, newList )
val diffResults = calculateDiff(diffUtil)
list = newList
diffResults.dispatchUpdatesTo(this)
}
fun getTaskAt(position: Int): Data {
return list[position]
}
}
task_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/taskHolder"
app:cardCornerRadius="15dp"
android:backgroundTint="#color/card"
app:cardElevation="3dp"
app:contentPadding="3dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
android:layout_marginEnd="3dp"
android:layout_marginStart="3dp" >
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="88dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/task_icon"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/task"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginStart="98dp"
android:layout_marginTop="4dp"
android:contentDescription="#string/task"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold|italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/taskDescription"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginEnd="100dp"
android:layout_marginBottom="4dp"
android:contentDescription="#string/task"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/task"
app:layout_constraintVertical_bias="1.0" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.924"
app:layout_constraintStart_toEndOf="#+id/task"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
I'm Java Developer so I cannot code with Kotlin but I'll show you how to get any view's position in RecyclerView
holder.itemView.setOnClickListener(view -> {
Toast.makeText(context, "This is position of your Every ItemViews", Toast.LENGTH_SHORT).show();
});
In your onBindViewHolder use this code holder.itemView.setOnClickListener and create new click listener. Here you can get the position of your items by coding and you can check by adding Toast.
your code lookalike below:-
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = list[position]
holder.itemView.findViewById<TextView>(R.id.task).text = item.task
holder.itemView.findViewById<TextView>(R.id.taskDescription).text = item.task_Details
holder.itemView.setOnClickListener(view -> {
Toast.makeText(context, "This is position of your Every ItemViews", Toast.LENGTH_SHORT).show();
});
}
Make sure to change JAVA to Kotlin of my code. If you any problem is causing, Let me know
Related
The above is what I am trying to achieve .
My recycle view item has two buttons . Both are hidden by default . On click of the item view should show the buttons for 1 sec. After it must hide . if I tap on either of these buttons , the timer should be reset for another 1 sec . Something similar to a debounce in rx java.
Need to do it with Kotlin coroutines .
I was able to achieve the above using kotlin coroutines jobs .
My layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="150dp"
android:layout_height="250dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginHorizontal="5dp"
android:elevation="5dp"
android:layout_gravity="bottom"
>
<TextView
android:id="#+id/product_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="#id/guideline_horizontal_top"
android:text="x2"
android:fontFamily="#font/gotham"
android:textColor="#color/dark_blue"
android:textSize="20sp"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline_horizontal_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent=".20"/>
<androidx.cardview.widget.CardView
android:id="#+id/part_card"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#id/guideline_horizontal_top"
app:layout_constraintBottom_toBottomOf="parent"
app:cardElevation="5dp"
android:clickable="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.google.android.material.button.MaterialButton
android:id="#+id/plus_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/transparent_dark_blue"
app:layout_constraintTop_toTopOf="parent"
android:insetTop="0dp"
app:cornerRadius="0dp"
android:text="ADD"
android:visibility="invisible"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/minus_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/transparent_dark_blue"
app:layout_constraintBottom_toBottomOf="parent"
android:insetBottom="0dp"
app:cornerRadius="0dp"
android:text="REDUCE"
android:visibility="invisible"/>
<TextView
android:id="#+id/partition_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="PART 1"
android:layout_margin="5dp"
android:textColor="#color/dark_blue"
android:fontFamily="#font/gotham_thin_font"
android:textStyle="bold"
/>
<TextView
android:id="#+id/items_left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Items left : "
android:layout_margin="5dp"
android:textColor="#color/dark_blue"
android:fontFamily="#font/gotham_thin_font"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"/>
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/partition_text"
app:layout_constraintBottom_toTopOf="#id/items_left"
android:layout_margin="5dp"
android:textColor="#color/dark_blue"
android:fontFamily="#font/gotham_thin_font"
android:textStyle="bold"
android:gravity="start"
android:text="Product name here"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
My addapter
class PartitionRecycleAdapter : RecyclerView.Adapter<PartitionRecycleAdapter.ViewHolder>() {
private var partitions: List<Selection<Partition>> = listOf()
private val coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.IO)
private var buttonManage: Job? = null
fun update(partitions: List<Selection<Partition>>) {
this.partitions = partitions
notifyDataSetChanged()
}
inner class ViewHolder(val binding: PartitionRecycleItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(partition: Selection<Partition>, position: Int) {
binding.apply {
partitionText.text = "Part ${partition.item.number}"
productName.text = partition.item.productName
val itemsLeftVar = partition.item.currentQty - partition.qty
itemsLeft.text = "Items left : $itemsLeftVar"
productCount.text = "X${partition.qty}"
if (partition.qty > 0) {
productCount.visibility = View.VISIBLE
} else {
productCount.visibility = View.INVISIBLE
}
Log.d(TAG, "bind: OUTER")
val listener = View.OnClickListener { view ->
buttonManage?.cancel()
buttonManage = coroutineScope.launch {
Log.d(TAG, "bind: Coroutine started")
delay(1000)
withContext(Dispatchers.Main) {
binding.plusButton.visibility = View.INVISIBLE
binding.minusButton.visibility = View.INVISIBLE
Log.d(TAG, "bind: Coroutine Ended")
}
}
if (view == partCard) {
binding.plusButton.visibility = View.VISIBLE
binding.minusButton.visibility = View.VISIBLE
}
if (view == plusButton) {
Log.d(TAG, "bind: PLUS")
if (itemsLeftVar > 0) {
partition.qty++
// notifyItemChanged(position)
}
}
if (view == minusButton) {
Log.d(TAG, "bind: MINUS")
if (partition.qty > 0) {
partition.qty--
// notifyItemChanged(position)
}
}
}
partCard.setOnClickListener(listener)
plusButton.setOnClickListener(listener)
minusButton.setOnClickListener(listener)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = PartitionRecycleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val partition = partitions[position]
holder.bind(partition, position)
}
override fun getItemCount(): Int {
return partitions.size
}
}
The problem is , when I add notifyItemChanged on my button click . Everything breaks. the button closes sometimes . sometimes not .
please help..
Hi I am using a recycler view with a card view, I have no idea why it is not scrolling smoothly. it stuck for a few seconds and shows the next content.
This is my xml for list item
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:focusable="true"
app:cardBackgroundColor="#color/colorAccent"
app:cardCornerRadius="10dp"
app:cardElevation="10dp" >
<LinearLayout
android:id="#+id/product_list_item_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/product_name_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="name"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/product_catagory_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="catagory"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/product_end_date_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="End Date"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
this is my recyclerViewAdapter
class ProductsRecyclerViewAdapter(private val clickListener: (Product) -> Unit): RecyclerView.Adapter<ProductsMyViewHolder>() {
private val productsList = ArrayList<Product>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductsMyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding: ProductsListItemBinding =
DataBindingUtil.inflate(layoutInflater, R.layout.products_list_item, parent, false)
return ProductsMyViewHolder(binding)
}
override fun getItemCount(): Int {
return productsList.size
}
override fun onBindViewHolder(holder: ProductsMyViewHolder, position: Int) {
holder.bind(productsList[position], clickListener)
}
fun setList(products: List<Product>) {
productsList.clear()
productsList.addAll(products)
}
}
class ProductsMyViewHolder(val binding: ProductsListItemBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(product: Product, clickListener: (Product) -> Unit) {
binding.productNameTextView.text = product.name
binding.productCatagoryTextView.text = product.catagory
binding.productEndDateTextView.text = convertLongToTime(product.end_date)
binding.productListItemLayout.setOnClickListener {
clickListener(product)
}
}
fun convertLongToTime(time: Long): String {
val date = Date(time)
val format = SimpleDateFormat("dd MMM yyyy")
return format.format(date)
}
}
This is my fragment where i initialise the ProductsRecyclerViewAdapter
private fun initRecyclerView() {
binding.productsRecyclerView.layoutManager = LinearLayoutManager(context)
adapter = ProductsRecyclerViewAdapter ({ selectedItem: Product -> listItemClicked(selectedItem)})
binding.productsRecyclerView.adapter = adapter
displayProductssList()
}
private fun displayProductssList() {
productsViewModel.products.observe(viewLifecycleOwner, Observer {
Log.i("MYTAG", it.toString())
adapter.setList(it)
adapter.notifyDataSetChanged()
})
}
any thoughts what I might be doing wrong here
your suggestion would be very helpful
thanks in advance
R
The only thing I see in your code is creating new SimpleDateFormat on every bind, it is definitely not free. Create single instance in adapter.
Also, maybe your products observer executes too often?
I am developing new app and how can I sort the company list based on Name ascending, descending order in my adapter?.
below my Adapter class
class SpectrumAdapter(
private val spectrumResponse: ArrayList <SpectrumResponseItem>
) : RecyclerView.Adapter<SpectrumViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpectrumViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.spectrum_list, parent, false)
return SpectrumViewHolder(view)
}
override fun getItemCount(): Int {
return spectrumResponse.size
}
override fun onBindViewHolder(holder: SpectrumViewHolder, position: Int) {
return holder.bind(spectrumResponse[position])
}
}
the adapter class.
class SpectrumViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val companyLogo: ImageView = itemView.findViewById(R.id.companyLogo)
private val companyName: TextView = itemView.findViewById(R.id.companyName)
private val companyWebsite: TextView = itemView.findViewById(R.id.companyWebsite)
fun bind(spectrum: SpectrumResponseItem) {
Glide.with(itemView.context).load(R.drawable.placehold).into(companyLogo)
companyName.text = spectrum.company
companyWebsite.text = spectrum.website
}
}
below list XML layout
<androidx.cardview.widget.CardView 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:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/companyLogo"
android:layout_width="45dp"
android:layout_height="26dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="11dp"
android:layout_marginRight="11dp"
android:padding="4dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="#+id/companyWebsite"
app:layout_constraintEnd_toStartOf="#+id/companyName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="#+id/companyWebsite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:layout_marginLeft="56dp"
android:layout_marginTop="40dp"
android:text="Company Website"
android:textSize="8sp"
app:layout_constraintBottom_toBottomOf="#id/companyLogo"
app:layout_constraintStart_toStartOf="#+id/companyLogo"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/companyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginEnd="286dp"
android:layout_marginRight="286dp"
android:text="Company Name"
android:textSize="8sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/companyLogo"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
I want to implement sorting function where user can sort companyName ascending and descending order how can I implement it?
You can add method sortAscending and sortDescending in your adapter. But you need to change your private val spectrumResponse: ArrayList to var because the data can be changed while sorting. here is full code example for adapter.
class SpectrumAdapter(
private var spectrumResponse: ArrayList <SpectrumResponseItem>
) : RecyclerView.Adapter<SpectrumViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpectrumViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.spectrum_list, parent, false)
return SpectrumViewHolder(view)
}
override fun getItemCount(): Int {
return spectrumResponse.size
}
override fun onBindViewHolder(holder: SpectrumViewHolder, position: Int) {
return holder.bind(spectrumResponse[position])
}
fun sortAscending() {
spectrumResponse = spectrumResponse.sortedBy { it.name }
notifyDataSetChanged()
}
fun sortDescending() {
spectrumResponse = spectrumResponse.sortedByDescending { it.name }
notifyDataSetChanged()
}
}
then you can call it in your button on you activity like this.
btn_sort_ascending.setOnClickListener {
adapter.sortAscending()
}
the btn_sort_ascending is the view id of your button.
the adapter is your created adapter.
I'm in the process of fiddling my way to a working app using Kotlin and I have hit a roadblock when trying to implement OnClickListeners for my three buttons. I have my RecyclerView populate properly, but despite following the recommendations on this SO post (except in Kotlin) and following the documentation, though I am still having trouble getting the implementation to work.
The code below is my adapter class for the implementation.
class BrowseHabitsAdapter(private val habits: ArrayList<Habit>) :
RecyclerView.Adapter<BrowseHabitsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.habit_card, parent, false)
return ViewHolder(itemView, object: HabitClickListener {
override fun onDecrease(position: Int) {
val streak = itemView.dayCounter.text.toString().toInt()
itemView.dayCounter.text = streak.dec().toString()
}
override fun onIncrease(position: Int) {
val streak = itemView.dayCounter.text.toString().toInt()
itemView.dayCounter.text = streak.inc().toString()
}
override fun onEdit(position: Int) {
TODO("Change Activity to Edit")
}
})
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentItem = habits[position]
holder.habitTitle.text = currentItem.title
holder.streak.text = currentItem.streak.toString()
}
override fun getItemCount() = habits.size
class ViewHolder(itemView : View, listener : HabitClickListener) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val habitTitle: TextView = itemView.habitTitle
val streak: TextView = itemView.dayCounter
val decreaseCounterButton : Button = itemView.decreaseCounterButton
val increaseCounterButton : Button = itemView.increaseCounterButton
val listener = listener
init {
decreaseCounterButton.setOnClickListener(this)
increaseCounterButton.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (itemView.id) {
itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
}
}
}
interface HabitClickListener {
fun onDecrease(position : Int)
fun onIncrease(position : Int)
fun onEdit(position : Int)
}
}
and the following is my XML code defining one of my cards:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
app:cardBackgroundColor="#eeeeee"
app:cardCornerRadius="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/cardHeader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/habitTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:text="#string/default_card_title"
android:textSize="18sp" />
<Space
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<ImageView
android:id="#+id/settingsIcon"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_gravity="bottom"
android:layout_marginRight="10dp"
app:srcCompat="#android:drawable/ic_menu_manage" />
</LinearLayout>
<LinearLayout
android:id="#+id/cardControls"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/decreaseCounterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="-"
android:textAllCaps="false"
android:textSize="30sp" />
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="#+id/dayCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:fontFamily="sans-serif-medium"
android:text="0"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold" />
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/increaseCounterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="+"
android:textSize="30sp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Any additional explanation that can be provided as to what I did wrong and what is going on in detail would be really appreciated!
You are in kotlin so need to implement View.OnClickListener you can directly use setOnClickListener on any view.
Inside your ViewHolder Class:
itemView.increaseCounterButton.setOnClickListener{
listener.onIncrease(this.layoutPosition)
}
itemView.decreaseCounterButton.setOnClickListener{
listener.onDecrease(this.layoutPosition)
}
It should be view?.id instead of itemView.id
override fun onClick(v: View?) {
when (v?.id) {
itemView.decreaseCounterButton.id -> listener.onDecrease(this.layoutPosition)
itemView.increaseCounterButton.id -> listener.onIncrease(this.layoutPosition)
}
}
Additionally, your code with bugs. You handle HabitClickListener only update UI, when you scroll your data will be update base on habits. It means it will be revert when you scroll. Make sure streak of model Habit is var
return ViewHolder(itemView, object: HabitClickListener {
override fun onDecrease(position: Int) {
habits[position].streak = habits[position].streak.dec()
itemView.dayCounter.text = shabits[position].streak.toString()
}
override fun onIncrease(position: Int) {
habits[position].streak = habits[position].streak.inc()
itemView.dayCounter.text = shabits[position].streak.toString()
}
override fun onEdit(position: Int) {
TODO("Change Activity to Edit")
}
})
I'm trying to hide part of my view in recycler when user toggles switch.
But when i toggle switch, sometimes it behaves in a strange way and hides only part of my view. It happens every 4 switch clicks (show-hide-show-hide), and i can't manage to solve this bug. Any advices what am i doing wrong?
There are screenshots of properly displayed view and awkwardly hidden view. As you can see, at the second screenshot seekbar with 2 image views is not fully hidden.
UPDATED: The problem is solved. Problem was in include tag. It somehow works wrong, the same layout in item file works fine.
Here is code for hiding logic:
itemView.light_switch.setOnCheckedChangeListener { _, isChecked ->
itemView.brightness.visibility = if (isChecked) View.VISIBLE else View.GONE
lightCallback(lamp, isChecked)
}
And here is my layout (recycler item):
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dp"
android:background="#1a1a1a">
<ImageView
android:id="#+id/light_icon_image_view"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/prod_foot" />
<TextView
android:id="#+id/light_name_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginStart="8dp"
android:fontFamily="sans-serif-medium"
android:textColor="#ffffff"
android:textSize="16sp"
android:textStyle="normal"
app:layout_constraintBottom_toBottomOf="#+id/light_icon_image_view"
app:layout_constraintStart_toEndOf="#+id/light_icon_image_view"
app:layout_constraintTop_toTopOf="#+id/light_icon_image_view"
tools:text="Floodlight 24 368 (01)" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:text="No group"
android:textColor="#7fffffff"
android:textSize="14sp"
android:textStyle="normal"
app:layout_constraintStart_toStartOf="#+id/light_name_text_view"
app:layout_constraintTop_toBottomOf="#+id/light_name_text_view" />
<android.support.v7.widget.SwitchCompat
android:id="#+id/light_switch"
style="#style/SwitchCompatStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/light_icon_image_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/light_icon_image_view"
app:thumbTint="#android:color/white" />
<include
android:id="#+id/brightness"
layout="#layout/brightness_seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/light_icon_image_view">
</include>
<ImageView
android:id="#+id/light_gradient_circle"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_marginTop="40dp"
app:layout_constraintStart_toStartOf="#+id/light_icon_image_view"
app:layout_constraintTop_toTopOf="#+id/light_icon_image_view"
app:srcCompat="#drawable/badge_color_wheel_active_block" />
</android.support.constraint.ConstraintLayout>
Include layout is provided below (seekbar with 2 images):
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:background="#1a1a1a"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="#+id/seekbar"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/seekbar"
app:srcCompat="#drawable/ic_dim_min" />
<SeekBar
android:id="#+id/seekbar"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginEnd="11dp"
android:layout_marginStart="11dp"
android:layout_marginTop="8dp"
android:max="255"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView2"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="#+id/seekbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/seekbar"
app:srcCompat="#drawable/ic_dim_max" />
</android.support.constraint.ConstraintLayout>
UPDATED: Adapter full code
class IndividualLightsAdapter(private val context: Context,
private val data: MutableList<Lamp>,
private val lightCallback: (Lamp, Boolean) -> Unit,
private val lightBrightnessCallback: (lamp: Lamp, brightness: Int) -> Unit)
: RecyclerView.Adapter<IndividualLightsAdapter.LightViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LightViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.light_item_new, parent, false)
return LightViewHolder(view)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: LightViewHolder, position: Int) {
holder.bind(position)
}
inner class LightViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(position: Int) {
val lamp = data[position]
itemView.light_icon_image_view.setImageResource(lamp.imageId)
itemView.light_name_text_view.text = lamp.customName
itemView.light_gradient_circle.visibility = if (lamp is SmartLamp) View.VISIBLE else View.INVISIBLE
itemView.light_switch.isChecked = lamp.isTurnedOn
itemView.light_switch.setOnCheckedChangeListener { _, isChecked ->
itemView.brightness.visibility = if (isChecked) View.VISIBLE else View.GONE
lightCallback(lamp, isChecked)
}
setSeekBar()
itemView.seekbar.progress = lamp.brightness
itemView.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
lightBrightnessCallback(lamp, progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
}
private fun setSeekBar() {
val gradient = GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
intArrayOf(ContextCompat.getColor(context, R.color.grad_start), (ContextCompat.getColor(context, R.color.grad_end))))
gradient.cornerRadius = context.resources.getDimension(R.dimen.corner_radius_outer)
val progressLayer = ClipDrawable(gradient, Gravity.START, ClipDrawable.HORIZONTAL)
val background = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(Color.BLACK, Color.BLACK))
background.cornerRadius = context.resources.getDimension(R.dimen.corner_radius_inner)
// TODO Calculate padding dynamically
val backgroundLayer = InsetDrawable(background,
context.resources.getDimension(R.dimen.padding_inset_left).toInt(),
context.resources.getDimension(R.dimen.padding_inset_top).toInt(),
context.resources.getDimension(R.dimen.padding_inset_right).toInt(),
context.resources.getDimension(R.dimen.padding_inset_bottom).toInt())
itemView.seekbar.thumb.setTint((ContextCompat.getColor(context, R.color.color_thumb)))
itemView.seekbar.progressDrawable = LayerDrawable(arrayOf<Drawable>(backgroundLayer, progressLayer))
}
}
}
You shouldn't hide the view that is an item of recyclerView.
It doesn't work properly because of its recycling mechanism.
You just need to remove/add the item to be able to do the same effect.
you should has the below methods on your RecyclerView adapter
private void deleteItem(int position) {
if (position != RecyclerView.NO_POSITION) {
myList.remove(position);
notifyItemRemoved(position);
}
}
private void addItem(int position, MyModel model) {
if (position != RecyclerView.NO_POSITION) {
myList.add(position, model);
notifyItemInserted(position);
}
}