ItemTouchHelper looses drag state when notifying adapter - android-recyclerview

I implemented a drag n drop by recyclerview and ItemTouchHelper.
I want to apply some changes when drag starts. So I'll notify adapter when onSelectedChanged gets ACTION_STATE_DRAG.
Notifying adapter just rebind items. It doesn't move items or add/remove item.
class ImageMoveCallback() : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int =
makeMovementFlags(RIGHT or LEFT or UP or DOWN, 0)
override fun isLongPressDragEnabled(): Boolean = true
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
// ...
return true
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
if (actionState == ACTION_STATE_DRAG) {
// notifying adapter
}
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
// ...
}
override fun isItemViewSwipeEnabled(): Boolean = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
}
But when adapter notifies, drag State will be lost. And I get ACTION_STATE_IDLE in onSelectedChanged and then clearView calls.
Is it normal to loose drag state when I notifying adapter?
How can I do this?

Related

How can I change recyclerview item background color permanent and transact new Fragment?

I want to change the color of recyclervView item that I clicked(so user can understand that already checked the detail of the item) and go detail fragment page. However this background color change must be permanent should I store it in livedata of recycler view items. I share my codes at the end I am new to android programming so please explain your solution for beginner and my english level is not good. Thanks for everything.
class AdapterRecycler() :
RecyclerView.Adapter<AdapterRecycler.ViewHolder>()
class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) {
val name: TextView = view.findViewById(R.id.gameId)
val score: TextView = view.findViewById(R.id.scoreId)
val genre: TextView = view.findViewById(R.id.genres)
val layout1: RelativeLayout = view.findViewById(R.id.rowlayout)
init {
// Define click listener for the ViewHolder's View.
//val textView : TextView = view.findViewById(R.id.gameId)
itemView.setOnClickListener {
layout1.setBackgroundColor(Color.rgb(224,224,224))
listener.onItemClick(adapterPosition)
}
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.text_row_item, viewGroup, false)
return ViewHolder(view, listenerItems)
}
class Games : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener {
override fun onItemClick(position: Int) {
// Fragment transaction to detail page
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainerView2, Details()).commit()
}
})
}
Should I store a boolean value in here to save item checked status?
data class Game(val name : String, val score : Int, val genres : Array<String>)
I tried solution at my codes and I get transaction but not the color changes of item layout.
I think it will be good if you'll update your Game model, after it became checked. Something like this:
data class Game(.., var isChecked: Boolean = false)
And inside your AdapterRecycler.onItemClickListener realization call ViewModel function to update isChecked value:
fun onItemChecked(position: Int) {
val item = TODO("get item by position from your live data")
item.isChecked = !item.isChecked
}
In addition, you should override your ViewHolder to setup a background rely on your isCheked value (it will be the same as must be after ViewHolder notify calls):
class ViewHolder(view: View, listener: onItemClickListener) : RecyclerView.ViewHolder(view) {
...
fun bind(item: Game) {
val backColor = if (item.isChecked) Color.GREEN else Color.BLUE
layout1.setBackgroundColor(Color.rgb(224,224,224))
}
}
Call bind function from your AdapterRecycler.onBindViewHolder this way:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), callback)
}
Don't forget to notify your adapter.
Guys thanks to your replies I reviewed my code and got solution.
Here is my edit at the code:
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
...
val color = if (_data[position].isChecked) Color.rgb(224,224,224) else Color.WHITE
viewHolder.layout1.setBackgroundColor(color)
...
}
That way I change the color of recyclerview item color since I change the fragments make the viewmodel at activity based and used it shared viewModel between fragments
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: GamesViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...
viewModel = ViewModelProvider(this)[GamesViewModel::class.java]
...
}
Then I added the boolean variable to my model.
data class Game(val name : String, val score : Int, val genres : Array<String>, var isChecked : Boolean = false)
Then I change the liveData's attribute of isChecked at the click listener.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter.setOnItemClickListener(object : AdapterRecycler.onItemClickListener {
override fun onItemClick(position: Int) {
viewModel= ViewModelProvider(requireActivity()).get(GamesViewModel::class.java)
val item = viewModel.liveData.value!!.get(position)
item.isChecked = true
// toGo next fragment
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainerView2, Details()).commit()
}
})
VoilĂ  we got the perfect result thanks for helping me, have a great day.

Calling method from Fragment in RecyclerView Adapter - Lateinit property textView has not been initialized

I have a list of items. When I swipe on an item, I want to update a textView in the Fragment.
I use a RecyclerView. In the Adapter, I detect when a user swipes something, and then I try to call a method in the Fragment to update a textview.
However, when I try it crashes with "LateInit Propery TextView has not been initialized". I have tried initializing the textView in the adapter instead, but I don't think that's correct and it seems impossible as findViewById doesn't really work in an adapter since the specific TextView is not on an item layout, but instead displayed in the Fragment Layout (and it needs to be that way as I don't want the textview on every single item).
My adapter (simplified)
class SwipeAdapter internal constructor(private val mCandidatesArrayList: ArrayList<SwipeCandidate>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val mSwipeFragment = SwipeFragment() //Here I initialize my fragment
fun createHelperCallback(): ItemTouchHelper.Callback {
return object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
val position = viewHolder.bindingAdapterPosition
mSwipeFragment.updateTextView() //This throws the error
}
}
}
}
}
And my Fragment (simplified):
class SwipeFragment : Fragment() {
private lateinit var textView : TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
textView = root.findViewById(R.id.textview) //initializing textview
}
fun updateTextView() {
textView.setText("Hello") //Setting the text
}
}
You are trying to get view from a fragment that is not open. In our fragment, as I understand it, the adapter is initialize, you need to pass a listener into it, which will be called after the swipe.
class SwipeAdapter internal constructor(var onSwiped: (position: Int) -> Unit = { }, private val mCandidatesArrayList: ArrayList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
fun createHelperCallback(): ItemTouchHelper.Callback {
return object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder,
): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
val position = viewHolder.bindingAdapterPosition
onSwiped(position)
}
}
}
}
fragment
class SwipeFragment : Fragment() {
private lateinit var textView: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
textView = root.findViewById(R.id.textview)
val adapter = SwipeAdapter({ position: Int ->
textView.setText("Hello")
}, arrayListOf())
}
}

Kotlin OnItemClickListener for a RecyclerView inside a Fragment

The problem is related to the fact that I don't manage to implement a OnItemClick listener for a RecyclerView that is located in a "mainFragment" by implementing the OnClickListener in the Adapter.
I would like my application (kotlin) to launch another fragment ("deletePage" in the code bellow) everytime an itemView (an ImageView) from the RecyclerView is clicked, this fragment would display the same photo in big.
My Adapter code is the following one:
class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
private var photo = emptyList<Photo>()
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)
)
}
override fun getItemCount(): Int {
return photo.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.longitude.text = photo[position].latitude
holder.itemView.latitude.text = photo[position].longitude
holder.itemView.imageView.load(photo[position].photo)
}
fun setData(photo: List<Photo>) {
this.photo = photo
notifyDataSetChanged()
}
}
And my mainFragment code is the following one:
class MainFragment : Fragment(){
private lateinit var myView: MyViewModel
private val adapter by lazy { MyAdapter() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_main, container, false)
//Recyclerview
val adapter = MyAdapter()
val recyclerView = view.recycler_view
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
myView = ViewModelProvider(this).get(MyViewModel::class.java)
myView.readPhoto.observe(viewLifecycleOwner, Observer {photo ->
adapter.setData(photo)
})
setHasOptionsMenu(true)
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_database, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when {
item.itemId == R.id.deleteAll -> findNavController().navigate(R.id.deletePage)
item.itemId == R.id.refresh -> {
Toast.makeText(activity, "yep", Toast.LENGTH_SHORT).show()
instertDataToDatabase()
}
}
if (item.itemId == R.id.deleteAll) {
}
return super.onOptionsItemSelected(item)
}
}
The objective is that when you click on an item of the RecyclerView the "findNavController().navigate(R.id.deletePage)" fragment is displayed but everytime I try to implement a solution the application crashes when clicking at an item of the RecyclerView. Right now the navigation works by the click on a button in the Menu at the toolbar but is not the ideal solution.
Any sort of help or advice would be very much appreciated!
Firstly you need to give click listener of your itemView in onBindViewHolder
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.longitude.text = photo[position].latitude
holder.itemView.latitude.text = photo[position].longitude
holder.itemView.imageView.load(photo[position].photo)
holder.itemView.setOnClickListener { navigateToFragment() }
}
For the navigation somehow you should have a context instance.
Here is the possible solutions that came up to my mind:
Give navigator instance to adapter
class Navigator(fragment: Fragment) {
private val fragmentRef = WeakReference(fragment)
fun navigate(){
// make your navigations here with using fragmentRef.get()
}
}
In your fragment:
private val navigator = Navigator(this)
...
val adapter = MyAdapter(navigator)
In your adapter:
class MyAdapter(private val navigator: Navigator) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
fun navigateToFragment(){
navigator.navigate()
}
Make interface for callback
2.1. Implement that interface in fragment and give adapter the interface instance
interface Navigable{
fun navigate()
}
In your fragment:
class MainFragment : Fragment(), Navigable{
...
override fun navigate(){
// make your navigation
}
val adapter = MyAdapter(navigator)
In your adapter:
class MyAdapter(private val navigable: Navigable) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
fun navigateToFragment(){
navigable.navigate()
}
2.2. Make the interface, but do not pass reference, use findFragment in adapter
In your adapter: override onAttachedToRecyclerView to find fragment
private lateinit var navigable: Navigable
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
navigable = recyclerView.findFragment<Fragment>() as Navigable
}
fun navigateToFragment(){
navigable.navigate()
}

Kotlin nested Recyclerview

I really appropriate it if somebody could help me out.
I apply my second RecyclerView with a custom swipe Button object, here fun handleSwipeClick is set to handle the action.
My question is: how can i make this function (handleSwipeClick) to handle each row specifically?? Like Delete this row item
Adapter #1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = baxters[position]
holder.listItem_time.text = item.intakeTime
holder.itemView.dose_recycler_view.apply {
dose_recycler_view.setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
dose_recycler_view.layoutManager = layoutManager
//Swipe action
val swipe = object: SwipeHelper(context,dose_recycler_view, 400){
override fun instaniateSwipeButton(
viewHolder: RecyclerView.ViewHolder,
buffer: MutableList<SwipeButton>
) {
// Adding Buttons
buffer.add(
SwipeButton(context,
"",
30,
R.drawable.ic_check_circle,
Color.parseColor("#66ff66"),
object : ButtonClickListener {
override fun handleSwipeClick(id: Int) {
// Click action
// TODO call to change LAST TAKEN and NEW INTAKE
Companion.errorToast(
context,
"Medicijn ingenomen. $id"
)
}
})
)
}
}
adapter = ClientDoseListAdapter(item.doses.toMutableList())
setRecycledViewPool(viewPool)
}
}
Adapter #2
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = doses[position]
/// DELETE THIS ROW
holder.med_name.text = item.medicineItem.name
holder.dose_amount.text = item.amount.toString()
}
First, create a delete method in ClientDoseListAdapter adapter, then call this method in the click action like,
fun delete(dose: Dose) {
val index: Int = doseList.indexOf(dose)
doseList.removeAt(index)
notifyDataSetChanged()
}
override fun handleSwipeClick(id: Int) {
// Click action
adapter.delete(adapter.getItem(viewHolder.adapterPosition))
}
Adapetr #1 looks like this:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = baxters[position]
holder.listItem_time.text = item.intakeTime
holder.itemView.dose_recycler_view.apply {
dose_recycler_view.setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
dose_recycler_view.layoutManager = layoutManager
// First init a new adapter
dosesAdapter = ClientDoseListAdapter(item.doses.toMutableList())
// Swipe action
val swipe = object: SwipeHelper(context, dose_recycler_view, 400){
override fun instaniateSwipeButton(
viewHolder: RecyclerView.ViewHolder,
buffer: MutableList<SwipeButton>
) {
// Adding Buttons
buffer.add(
SwipeButton(context,
"",
30,
R.drawable.ic_check_circle,
Color.parseColor("#66ff66"),
object : ButtonClickListener {
override fun confirmDoseTaken(id: Int) {
// Click action
// TODO call to change LAST TAKEN and NEW INTAKE
Companion.errorToast(
context,
"Medicijn ingenomen. $id"
)
// i can call removeItem method in adapter
dosesAdapter.removeItem()
}
})
)
}
}
// set recyclerView adapter
adapter = dosesAdapter
setRecycledViewPool(viewPool)
}
}

I've tried to make a RecyclerView with an Adapter but I cannot see the layout?

I've tried to build a recyclerview with an adapter class and cardview layout however even though the code runs I cannot see the list with cardview (I just get a blank recyclerview)?
SpeakerAdapter.kt
class SpeakerAdapter (val speakers: ArrayList<String>): RecyclerView.Adapter<SpeakerAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val speakerName: TextView = itemView.findViewById(R.id.name)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.speakerName.text = speakers[position]
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val View = LayoutInflater.from(parent.context).inflate(R.layout.speaker_list, parent, false)
return ViewHolder(View)
}
override fun getItemCount() = speakers.size
}
Speaker.kt
class Speaker : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
setContentView(R.layout.activity_speaker)
val speakers : ArrayList<String> = ArrayList()
for (i in 1..100){
speakers.add("Speaker 1 #$i")
recyclerView_speaker.layoutManager = LinearLayoutManager(this)
recyclerView_speaker.adapter = SpeakerAdapter(speakers)
}
}}
It's a bit hard to debug without the xml. But here goes nothing:
I think it'd be worth a shot modifying your view holder class. The reference for the text view is being set when you init the view holder and the layout may not be inflated yet. Try finding the reference when you bind the data to the view to avoid this issue.
Try this:
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(name: String?) {
itemView. name.text = name
}
}
and then modify your adapter to call this method
class SpeakerAdapter (val speakers: ArrayList<String>): RecyclerView.Adapter<SpeakerAdapter.ViewHolder>() {
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(speakers[position])
}
}
PS.: it'd be a good idea to call your view holder something else. ViewHolder is a name that is already used by the android SDK. Ex.: SpeakerViewholder