I have three fragments in my app Home
, Profile
and Detail
.In Home fragment I am showing a list of users. When user clicks on any item in the list it will open detail fragment and in the detail fragment I want to show user's details. I am using jetpack navigation component in my app. I have no idea of how I can pass data using navigation component to another fragment.
Below is my code:
nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/nav_graph"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.studious.HomeFragment"
android:label="Home"
tools:layout="@layout/fragment_home" >
<action
android:id="@+id/action_homeFragment_to_detailFragment"
app:destination="@id/detailFragment" />
</fragment>
<fragment
android:id="@+id/profileFragment"
android:name="com.example.studious.ProfileFragment"
android:label="Profile"
tools:layout="@layout/fragment_profile" />
<fragment
android:id="@+id/detailFragment"
android:name="com.example.studious.DetailFragment"
android:label="fragment_detail"
tools:layout="@layout/fragment_detail" />
</navigation>
UserAdapter.kt
class UserAdapter(private val context: Context, private val userList:List<User>): RecyclerView.Adapter<UserAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserAdapter.ViewHolder {
return ViewHolder(UserRowBinding.inflate(LayoutInflater.from(parent.context),parent,false))
}
override fun onBindViewHolder(holder: UserAdapter.ViewHolder, position: Int) {
val model = userList[position]
holder.binding.name.text = model.name
holder.binding.city.text = model.city
holder.binding.email.text = model.email
holder.binding.layout.setOnClickListener {
Toast.makeText(context,model.name,Toast.LENGTH_SHORT).show()
}
}
override fun getItemCount(): Int {
return userList.size
}
class ViewHolder(val binding:UserRowBinding): RecyclerView.ViewHolder(binding.root)
}
Someone let me know how can I achieve the desired functionality.