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 :
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:
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.
I think you will need to bind the handlers
as well, maybe something like this in onCreate
:
MyHandlers handlers = new MyHandlers();
binding.setHandlers(handlers);