使用DataBinding,首先在build.gradle (Module: app)裡增加
android {
....
dataBinding {
enabled = true
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
User:
資料物件可以有兩種方法做綁定:
public class User {
public final String firstName;
public final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
public class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 在onCreate階段產生binding物件
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// 產生資料物件
User user = new User("Test", "User");
// 綁定到物件上?
binding.setUser(user);
}
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬