我正在尝试从活动中调用视图模型中的方法,但没有调用该方法。
LoginViewModel
class LoginViewModel : ViewModel() {
private var mLoginData: MutableLiveData<LoginModal>? = null
private var loginRepository: LoginRepository? = null
fun initLogin(jsonObject: JsonObject) {
if (mLoginData != null) {
return
}
loginRepository = LoginRepository().getInstance()
mLoginData = loginRepository?.getLoginData(jsonObject)
}
fun getLoginData(): MutableLiveData<LoginModal>? {
return mLoginData
}
}
LoginActivity
class LoginActivity : AppCompatActivity() {
var etUsername: EditText? = null
var etPassword: EditText? = null
var loginViewModel: LoginViewModel? = null
private var mLoginData: MutableLiveData<LoginModal>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimary);
etUsername = findViewById(R.id.et_username)
etPassword = findViewById(R.id.et_password)
loginViewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
}
fun login(view: View) {
val jsonObject = JsonObject()
jsonObject.addProperty("userId", etUsername!!.text.toString())
jsonObject.addProperty("password", etPassword!!.text.toString())
jsonObject.addProperty("deviceId", "45684")
loginViewModel?.initLogin(jsonObject)
Log.d("Login Activity", "Login Data : " + mLoginData)
}
}
login
方法onClick
按钮调用,但不调用initLogin
。
请帮忙。谢谢
更新:
XML
login
的调用位置。
<ImageButton
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/ic_login"
android:background="@android:color/transparent"
android:onClick="login"/>
1. XML-
<ImageButton
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/ic_more"
android:background="@android:color/transparent"
android:onClick="login"/>
2. Activity-
lateinit var viewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel=ViewModelProviders.of(this).get(LoginViewModel::class.java)
}
fun login(view: View) {
Log.d("Activity:", "login method called")
viewModel.initLogin()
}
3. View Model
fun initLogin() {
Log.d("Login View model:", "init Login called")
}
我已经创建了参考上述问题的示例。但它对我来说效果很好。请参考我的示例代码。
尝试代码:
<data>
<veriable name="login" type="com.example.databinding.Login"/>
</data>
<ImageButton
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/ic_login"
android:background="@android:color/transparent"
android:onClick="@{login}"/>