Android~DataBinding 使用,androidsdk 开发实例
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
notifyPropertyChanged(BR.pwd);
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
@Bindable
public String getLoginTime() {
return loginTime;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
notifyPropertyChanged(BR.loginTime);
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="com.example.myapplication.UserInfo" />
<variable
name="Activity"
type="com.example.myapplication.MainActivity" />
</data>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/container"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center_horizontal|top">
<EditText
android:id="@+id/name_et"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:singleLine="true"
android:text="@={user.name}"
android:hint="用户名"/>
<EditText
android:id="@+id/pwd_et"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="@={user.pwd}"
android:inputType="numberPassword"
android:hint="密码"/
<TextView
android:id="@+id/login_time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.loginTime}"/>
<Button
android:id="@+id/login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{Activity.userLogin}"
android:text="登录"/>
</LinearLayout>
</layout>
如何进行单向绑定?
1、UserInfo 继承自 BaseObservable
2、为 UserInfo 中需要绑定的 get 方法添加注解@Bindable
,set 方法添加notifyPropertyChanged(BR.loginTime);
3、如要进行双向绑定,再单向绑定基础上添加等号,如android:text="@={user.pwd}"
Activity 中如何使用 DataBinding?
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.myapplication.databinding.TestMainBinding;
public class MainActivity extends Activity {
final static String TAG = "Main";
private UserInfo user;
private TestMainBinding binding;
private Time mTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.test_main);
mTime = new Time();
binding = DataBindingUtil.setContentView(MainActivity.this,R.layout.test_main);
user = new UserInfo("","");
binding.setUser(user);
binding.setActivity(this);
评论