昨天介紹了databinding的基本使用,那麼當需要改變事件的值又該怎麼寫呢
@{() -> view.onSendMsg()}
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click2"
android:textSize="40sp"
android:onClick="@{() -> view.onSendMsg()}"/>
可以帶入position的值進去@{() -> view.onSendMsg(dataItem.position)}
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click3"
android:textSize="40sp"
android:onClick="@{() -> view.onSendMsg(dataItem.position)}"/
@{handler::onSendMsg}
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{handler::onSendMsg}"
android:text="click"
android:textSize="40sp" />
or@{handler.onSendMsg}
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{handler.onSendMsg}"
android:text="click"
android:textSize="40sp" />
ClickHandler
public class ClickHandler {
Activity activity;
public ClickHandler(Activity mMainActivity)
{
activity = mMainActivity;
}
public void onSendMsg(View view){
Toast.makeText(activity,"clickHandler",Toast.LENGTH_SHORT).show();
Log.d("123","clickHandler");
}
}
MainActivity2
public class MainActivity2 extends AppCompatActivity implements MainActivity2View.View{
ActivityMain2Binding main2Binding;
DataItem dataItem;
int count =0;
ClickHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
main2Binding=DataBindingUtil.setContentView(this,R.layout.activity_main2);
dataItem=new DataItem();
dataItem.setName("eles");
dataItem.setPasswd("213457");
main2Binding.setDataItem(dataItem);
main2Binding.setView(this);
handler=new ClickHandler(MainActivity2.this);
main2Binding.setHandler(handler);
}
@Override
public void onSendMsg(int position) {
}
@Override
public void onSendMsg() {
}
}
tips:將點擊事件寫在ClickHandler時,如果把class name第一個英文字是小寫,databinding會一直抱錯。
那按鈕的點擊事件就到此結束