Note: also review the edited code at the bottom for further development.
How can we attach / assign an event to spinner using data binding, specifically by listener bindings. Here is an article regarding the usage of data binding. So, I was trying the code and failed to assign an event.
on Android Studio 3.2.1
activity_parents_reg.xml
<data>
<import type="java.util.ArrayList" />
<variable name="handlers"
type="com.example.myUser.myapplication.custom.MyHandlers"
/>
<variable
name="cities"
type="ArrayList<String>"
/>
<data>
<Spinner
android:id="@+id/dd_city"
android:entries="@{cities}"
android:onClick="@{() -> handlers.onClickFriend()}"
style="@style/dropdown"
/>
MyHandlers.java
public class MyHandlers {
public void onClickFriend(View view) {}
}
ParentsReg.java
// Data binding
ActivityParentsRegBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_parents_reg);
binding.setCities(ConstData.getCitiesList());
binding.setHandlers(new MyHandlers());
Here is the error receiving on compilation:
Found data binding errors.
****/ data binding error ****msg:cannot find method onClickFriend() in class
com.example.myUser.myapplication.custom.MyHandlers
file:/home/myUser/AndroidStudioProjects/MyApplication/app/src/main/
res/layout/activity_parents_reg.xml loc:103:37 - 103:60
****\ data binding error ****
Edited:
Now, After observing and experimenting. I got the another perspective of my code that ensures syntax is fine.
Actually the spinner is making problem. Maybe it needs an adapter to set the events.
Here it is, working around to Button
having little bit changes to code as well:
// Activity layout changes.
<Button
android:id="@+id/btn_reg_submit"
android:text="Submit"
android:onClick="@{(view) -> handlers.onClickFriend(view)}"
style="@style/btn_secondary"
/>
// MyHandlers class changes.
public class MyHandlers {
private Context _context;
public MyHandlers(Context context) {
_context = context;
}
public void onClickFriend(View view) {
Toast.makeText(_context, "Button Clicked", Toast.LENGTH_SHORT).show();
}
}
// Activity class changes.
binding.setHandlers(new MyHandlers(context));
Still stuck with spinner.
Hopefully I will get the answer.