提问人:Techchai Mobile 提问时间:11/4/2023 最后编辑:Techchai Mobile 更新时间:11/5/2023 访问量:17
如何:使用可观察状态流隐藏数据绑定中的视图
How to Hide the views in Data binding with observable State flow
问:
如果数据类中的值为空或 null,我想隐藏视图。我正在从 API 获取数据并分配给视图模型中的 stateflow ui 状态。
这是我在布局中添加的代码
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.view.View"/>
<variable name="headlines" type="com.example.core.model.Headlines"/>
</data>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardview_lay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/mtrl_card_spacing"
android:layout_marginTop="12dp"
android:layout_marginRight="@dimen/mtrl_card_spacing"
android:scrollbars="none">
<ImageView
android:id="@+id/news_banner"
android:layout_width="match_parent"
android:layout_height="180dp"
android:adjustViewBounds="true"
android:fitsSystemWindows="true"
android:visibility="@{headlines.urlToImage != null ? View.VISIBLE: View.GONE}"
android:scaleType="centerCrop" />
</com.google.android.material.card.MaterialCardView>
视图模型
@HiltViewModel
class NewsViewModel @Inject constructor(
private val newsRepository: NewsRepository,
private val userPreferencesRepository: UserPreferencesRepository
) : ViewModel() {
private var _uiState = MutableStateFlow(UiState(isLoading = false))
val uiState: StateFlow<UiState> = _uiState
fun fetchNewsHeadLines() {
viewModelScope.launch {
val response = newsRepository.getNewsHeadlines()
response.collect {
Log.d("RAVU", "articles: ${it.size}")
val headlines: List<Headlines> = it
_uiState.update {
_uiState.value.copy(isLoading = false, newsList = headlines)
}
}
}
}
}
data class UiState(
val isLoading: Boolean = false,
val newsList: List<Headlines> = emptyList(),
val language: String? = null,
val category: String = ""
)
使用此代码,我看到图像布局隐藏,但即使图像可用,它也会隐藏,并且还看到图像视图首先可见,然后视图消失了。它就像有时闪烁列表中的某些行项以显示和隐藏 ImageView 一样。
处理此用例的最佳方法是什么?
答: 暂无答案
评论