Im doing an activity to show a profile that contains some cards with sports related to it, the idea is to see three cards at a time and be able to scroll the cards to see the next ones.
This is the code on the profile activity where I take the RecyclerView
and set the linearLayoutManager
and the adapter
:
private lateinit var sportRV: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_profile)
sportRV = findViewById(R.id.idRVSport)
... Some Other Code ...
val sportModelArrayList: ArrayList<SportModel> = ArrayList()
sports.map { sportModelArrayList.add(SportModel(it)) }
val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
sportRV.layoutManager = linearLayoutManager
val sportAdapter = SportAdapter(this, sportModelArrayList)
sportRV.adapter = sportAdapter
}
This is the adapter
class:
class SportAdapter(private val context: Context, sportModelArrayList: ArrayList<SportModel>) :
RecyclerView.Adapter<SportAdapter.ViewHolder>() {
private var sportModelArrayList: ArrayList<SportModel>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.card_view, parent, false)
val lp = view.layoutParams
lp.width = parent.measuredWidth / 3
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val model: SportModel = sportModelArrayList[position]
holder.sportName.text = model.sportName
}
override fun getItemCount(): Int {
return sportModelArrayList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val sportName: TextView
init {
sportName = itemView.findViewById(R.id.sportName)
}
}
init {
this.sportModelArrayList = sportModelArrayList
}
}
This is the section of the profile_activity.xml
where the RecyclerView is used:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/idRVSport"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
The RecyclerView works when I have the device verticaly, but the cards disappear when I rotate it, although the onCreateViewHolder
function is still called, and the CardViews are created, just not shown. The cards reappear when I put it back vertically
onCreate
, but it's better to put that retrieval in a ViewModel to avoid having to read from disk after each screen rotation.