Home > front end >  RecyclerView items using ConstraintLayout are not filling the entire width of the screen even though
RecyclerView items using ConstraintLayout are not filling the entire width of the screen even though

Time:11-17

I am attempting to set up a recycler view, with the elements being displayed by it using a ConstraintLayout. I used the Preview from Android Studio designer Preview from Android Studio designer

Actual result

Actual result on emulated Pixel 5 running API 30/Android 11 Actual result on emulated Pixel 5 running API 30/Android 11

CodePudding user response:

Your code here:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
    return RecipeViewHolder(
        RecipeListEntryBinding.inflate(
            LayoutInflater.from(
                parent.context
            )
        )
    )
}

does not inflate the view in the context of the parent view, so some layout parameters will not be treated as you expect. In this case, it can't have a width of match_parent if it doesn't know who its parent is. Change it to:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
    return RecipeViewHolder(
        RecipeListEntryBinding.inflate(
            LayoutInflater.from(
                parent.context
            ),
            parent,
            false
        )
    )
}

Also, a tip. You don't need to create a companion object just to hold your DiffCallback. And you don't need a property to hold an object either. For cleaner code, instead of

companion object {
    private val DiffCallback = object : DiffUtil.ItemCallback<Recipe>() {
        //...
    }
}

you could put

private object DiffCallback: DiffUtil.ItemCallback<Recipe>() {
    //...
}
  • Related