Когда я звоню в DispatchupDateSto, снова называется OncreateViewholderAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Когда я звоню в DispatchupDateSto, снова называется OncreateViewholder

Сообщение Anonymous »

class MainActivity : AppCompatActivity() {
var uiState by mutableStateOf(Item("", "Initial Call"))

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)

val adapter = MyAdapter()
recyclerView.adapter = adapter
Log.d("[HelloTesting]", "data hashcode is before copy is ${uiState.hashCode()}")

adapter.update(uiState)

lifecycleScope.launchWhenCreated {
delay(5000)
uiState = uiState.copy("Banner 2", "Banner 2 ${Random.nextInt()}")
Log.d("[HelloTesting]", "data hashcode is after copy is ${uiState.hashCode()}")
adapter.update(uiState)
}
}
}
< /code>
Это класс пункта < /p>
data class Item(
val imageUrl: String,
val title: String,
)
< /code>
class SpotlightViewHolder(val compose: ComposeView) :
RecyclerView.ViewHolder(compose)

internal class MyAdapter() : RecyclerView.Adapter() {
private val items = mutableListOf(
Item("Banner1 ", "Banner 1 ${Random.nextInt()}"),
)

private lateinit var mContext: Context

private var isExecutedPos = mutableMapOf(0 to false, 1 to false, 2 to false)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpotlightViewHolder {
mContext = parent.context
val holder = SpotlightViewHolder(ComposeView(parent.context))
Log.d("[HelloTesting]", "onCreate ${holder.hashCode()}")
return holder
}

override fun onBindViewHolder(holder: SpotlightViewHolder, position: Int) {
Log.d("[HelloTesting]", "onBindViewHolder ${holder.hashCode()}")
Log.d("[HelloTesting]", "BINDING $position")

if (isExecutedPos[position] == true) {
return
}
isExecutedPos[position] = true

Log.d("[HelloTesting]", "this code is working or not $position")
holder.compose.apply {
setContent {
Log.d("[HelloTesting]", "Composing $position and ${items[0]} .. and ${items[0].hashCode()}")
Count(items[0])
}
}
}

@SuppressLint("NotifyDataSetChanged")
fun update(data: Item) {
val list = listOf(data)
applyDataSetChanged(list)
}

fun applyDataSetChanged(newPayComponentModel: List) {
val diffCallback = PayComponentDiffUtil(items, newPayComponentModel)
val diffResult = DiffUtil.calculateDiff(diffCallback)
items.clear()
items.addAll(newPayComponentModel)
diffResult.dispatchUpdatesTo(this)
}

override fun getItemCount() = items.size
}
< /code>
@Composable
fun Count(count: Item) {
var showBanner by remember { mutableStateOf(true) }
LaunchedEffect(count) {
showBanner = false
delay(3000)
showBanner = true
}

AnimatedVisibility(
visible = showBanner,
enter = fadeIn(animationSpec = tween(durationMillis = 3000)),
exit = fadeOut(animationSpec = tween(durationMillis = 3000))
) {
Text(text = "Hello Times of count ${count.title}", color = Color.Red, fontSize = 12.sp)
Spacer(
modifier = androidx.compose.ui.Modifier
.height(40.dp)
.background(Color.Cyan)
)
}
}
< /code>
internal class PayComponentDiffUtil(
private val oldPayComponentList: List,
private val newPayComponentList: List,
) : DiffUtil.Callback() {
override fun getOldListSize() = oldPayComponentList.size

override fun getNewListSize() = newPayComponentList.size

override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldPayComponentList[oldItemPosition].hashCode() == newPayComponentList[newItemPosition].hashCode()
}

override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldPayComponentList[oldItemPosition] == newPayComponentList[newItemPosition]
}
}
< /code>
I was integrating Compose with RecyclerView but not able to use compose state management because of onCreateViewholder is calling again when sending an update to adaptor on data changes.
Ideally when only data is changed then onCreateViewholder should not called again.

Подробнее здесь: https://stackoverflow.com/questions/794 ... lled-again
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»