使用DataBinding库绑定事件 [英] Using DataBinding library for binding events

查看:387
本文介绍了使用DataBinding库绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Android M附带的 DataBinding Library 绑定xml中的视图。我正在从 Android开发人员,并逐步实施。对于视图的属性,如可见性,文本它的工作正常,但如果我尝试绑定onclick,它不能按预期的方式工作。以下是我迄今为止尝试过的示例代码:

I'm trying to bind events with views in xml using DataBinding Library shipped with Android M. I'm following examples from Android Developers and implementing step-by-step. for the view's attributes like visibility,text its working fine but if I try to bind with onclick, it doesn't work as expected. Here's the sample code that I've tried so far:

 <data>
    <import type="android.view.View"/>
    <variable name="user" type="com.example.databinding.User"/>
    <variable name="handlers" type="com.example.databinding.MyHandlers"/>
</data>

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{user.firstName}"
    android:visibility="@{user.isFriend ? View.VISIBLE : View.GONE}" />
 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    android:id="@+id/button"
    android:layout_gravity="left"
    android:onClick="@{handlers.onClickFriend}"/>

MainActivity:

MainActivity :

  public class MainActivity extends AppCompatActivity {

  User user;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = 
    DataBindingUtil.setContentView(this,R.layout.activity_main);
    user = new User("Pankaj","Kumar",true,true);
    binding.setUser(user);
   }
 }

MyHandlers:

MyHandlers:

public class MyHandlers {
public void onClickFriend(View view){
    Log.i(MyHandlers.class.getSimpleName(),"Now Friend");
}

public void onClickEnemy(View view){
    Log.i(MyHandlers.class.getSimpleName(),"Now Enemy");
  }
}

我只写了所需的代码来提高可读性。

I've written only required code to improve readability. Could someone help me on this.

推荐答案

我想你将需要绑定处理程序也可以在 onCreate 中这样做:

I think you will need to bind the handlers as well, maybe something like this in onCreate:

MyHandlers handlers = new MyHandlers();
binding.setHandlers(handlers);

这篇关于使用DataBinding库绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆