I'm trying to use DataBinding in Android. But i have a question in my mind.
I want to send edittext's text to binding functions inside xml. I mean; When the login button is clicked, I want to get the current username and password from the xml IDs. Is it possible?
Here what I want:
android:onClick="@{() -> login.onLogin(login_edt_username.text, login_edt_password.text)}"
My Current Usage:
Code:
@Override
protected void onStart() {
super.onStart();
binding= DataBindingUtil.setContentView(this,R.layout.activity_login);
}
@Override
public void onLogin() {
login(binding.loginEdtUserName.getText(),binding.loginEdtPassword.getText());
}
Xml:
<layout>
<data>
<variable
name="login"
type="interfaces.login.LoginInterface" />
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.friends.LoginActivity">
<EditText
android:id="@+id/login_edt_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
<EditText
android:id="@+id/login_edt_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/login_edt_user_name"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/login_btn_sign_in"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> login.onLogin()}"
android:layout_below="@+id/login_edt_password"
android:text="SIGN IN" />
<Button
android:id="@+id/login_btn_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> login.onRegister()}"
android:layout_below="@+id/login_btn_sign_in"
android:text="REGISTER" />
</RelativeLayout>
Thanks in advance.
This can be solved using 2-way Databinding (available since version 2.1 of the Gradle Plugin).
Alternative 1:
Import
android.view.View
in your XML:Then, you will be able to reference some attributes of your Views directly in XML. In Lambda Expressions, like you're using, you can also use the Views like you would in Java. Concretely:
Alternative 2: Using a POJO. Given a POJO modelling your credential information, such as
, after declaring this model in your XML
You could do:
and finally, to fit your requirement