【发布时间】:2021-04-30 06:08:18
【问题描述】:
首先我在布局文件中声明了变量
<data>
<variable
name="signUpViewModel"
type="ac.connect.ui.signup.SignUpViewModel" />
</data>
现在我正在尝试使用 StringExtension 类的函数,该函数将字符串值作为参数并将结果设置为 textView
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="20dp"
android:textStyle="bold"
android:background="#C1BDBD"
android:textColor="#3D3C3C"
app:capitalizeFirstLetter="@{signUpViewModel.name}" />
首字母大写函数
fun capitalizeFirstLetter(value: String): String {
var ans = ""
val words = value.split(" ")
words.forEach {
ans += it.capitalize() + " "
}
return ans
}
视图模型
class SignUpViewModel(private val setProfileUseCase: SetProfileUseCase) :
ViewModel() {
private val _profile = MutableLiveData<ProfileModel>()
val profile: LiveData<ProfileModel>
get() = _profile
private val _name = MutableLiveData<String>()
val name: LiveData<String>
get() = _name
fun setName(name: Editable) {
_name.value = name.toString()
}
fun setProfileData() {
viewModelScope.launch {
val profile = ProfileModel(
name = "kamal nayan",
branch = "CSE",
gender = "Male",
mobileNumber = "+91-73555555517",
rollNo = "GCS/345353",
uid = "ghafagaraggGGG"
)
val response = setProfileUseCase.invoke(profile)
_profile.value = profile
response.successOrError(::handleProductDetailsSuccess, ::handleSignUpFailure)
}
}
private fun handleProductDetailsSuccess(response: Boolean) {
_name.value = "User Data Uploaded Successfully"
}
private fun handleSignUpFailure(failure: Failure, error: ErrorResponse?) {
Timber.log(Log.ERROR, error?.message)
}
}
片段代码:
class SignUpFragment : Fragment(R.layout.fragment_sign_up) {
private val viewModel: SignUpViewModel by viewModel()
private var binding by autoCleared<FragmentSignUpBinding>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentSignUpBinding.bind(view)
binding.signUpViewModel = viewModel
binding.lifecycleOwner = this
binding.signUp.setOnClickListener {
viewModel.setProfileData()
}
}
companion object {
fun newInstance(): SignUpFragment {
return SignUpFragment()
}
}
}
输出是空白的,就像 textView 中没有文字一样
请帮我解决这个问题,在此先感谢。
【问题讨论】:
-
发布您的 ViewModel 和 Fragment/Activity
-
@OhhhThatVarun 都发布了。
-
StringExtensions是类还是对象? -
这是一个函数,最近我更新了这个问题,现在我们不需要制作变量....制作了一个绑定适配器....但是如何从布局中观察实时数据
-
检查我的新答案。
标签: android kotlin user-interface data-binding