【发布时间】:2021-03-23 19:00:50
【问题描述】:
更新:
我发现异步任务有问题,同时设置LiveData
我在我的应用程序中使用 MVVM,并尝试使用 Jetpack 数据绑定将 Livedata 绑定到 TextView。
我在 Viewmodel 的 Log.d() 中获得了正确的值,但数据未显示在屏幕上。
有人能猜出我错过了什么吗?
我的 XML 文件
(fragment_lobbyleader.xml)
<data >
<variable
name="viewmodel"
type="com.example.beerrallye.lobby.newLobbyData.LobbyViewModel" />
</data>
<TextView
android:id="@+id/lobbyleader_lobbyCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@{viewmodel.lobbyID}"
android:textColor="@color/black"
app:layout_constraintBottom_toTopOf="@id/lobbyleader_player_textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
我的视图模型
class LobbyViewModel(private val lobbyRepository: LobbyRepository) : ViewModel() {
private val _lobbyID = MutableLiveData<String?>()
val lobbyID : LiveData<String?> = _lobbyID
fun createLobby(lobby: Lobby) {
viewModelScope.launch {
val result = lobbyRepository.createLobby(lobby)
Log.d("Lobby", "Viewmodel Data: ${result}")
if (result is Result.Success) {
_lobbyID.value = result.data.lobbyID
Log.d("Lobby", "Viewmodel Data: ${_lobbyID.value}")
}
}
}
我的片段
class LobbyLeaderFragment : Fragment() {
private val lobbyViewmodel: LobbyViewModel by viewModels {
LobbyViewModelFactory((activity?.application as AppApplication).lobbyRepository)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: FragmentLobbyleaderBinding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_lobbyleader,
container,
false
)
binding.viewmodel = lobbyViewmodel
binding.lifecycleOwner = viewLifecycleOwner
lobbyViewmodel.lobbyID.observe(viewLifecycleOwner, {
Log.d("Lobby", "LobbyCode: $it")
})
return binding.root
}
}
【问题讨论】:
标签: android kotlin android-livedata android-databinding