Reputation: 173
I have the following code:
(setViewHolder is called in Adapter's OnCreateViewHolder)
override fun setViewHolder(parent: ViewGroup): BaseViewHolder<Task> {
return if (isHorizontal) {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.horizontal_recycler_item, parent, false)
// Overriding default width
val params = view.layoutParams as ViewGroup.MarginLayoutParams
params.width = ((parent.width / 2.15) - params.marginStart - params.marginEnd).toInt()
view.layoutParams = params
TaskViewHolder(view)
} else {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.details_list_item, parent, false)
TaskViewHolder(view)
}
}
And everything works fine until I refresh the fragment. And that's when the RecyclerView just becomes invisible. However, removing the line, where I set the width, from setViewHolder
solves my issue.
What causes this?
Upvotes: 1
Views: 192
Reputation: 571
The reason it becomes invisible is because you set width
with parent.width
directly,
We can not get the true value from parent.width
when it is not measured.
view.measure(View.MeasureSpec, View.MeasureSpec)
After view.measure
, we can call view.measuredWidth
or view.measuredHeight
to get the true value and calculate the size you want.
(view.measuredWidth / 3).toInt()
You just only need to find out what MeasureSpec you need to calculate.
But note that measure
will caused a heavy-weight in loading, you need to use it carefully.
We can get screen resolution in DisplayMetric
by context.resources.displayMetric
, so you can calculate the size you want
(context.resources.displayMetric.width / 3).toInt()
Upvotes: 1