事件處理類
public class EventHandlers {
public void handleClick ( View view){
Toast.makeText(view.getContext(),"clicked",Toast.LENGTH_SHORT).show();
}
}
xml文件中
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
type="com.lefeee.dbdemoapplication.bean.User"
name="user" />
/*事件的類型和名稱*/
<variable
type="com.lefeee.dbdemoapplication.EventHandlers"
name="handlers" />
</data>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.lefeee.dbdemoapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.username}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.password}"
android:clickable="true"
android:onClick="@{ handlers.handleClick}" /> // 添加綁定事件
</LinearLayout>
</layout>
activity中
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user1 = new User("yuanlin", "123456");
binding.setUser( user1 );
/*添加綁定事件*/
EventHandlers mHandler = new EventHandlers();
binding.setHandlers(mHandler);
}
}