I want to use onClick method in fragment but data binding doesn't see method.
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
FragmentTodayBinding fragmentTodayBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_today, container, false);
View view = fragmentTodayBinding.getRoot();
final MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
fragmentTodayBinding.setMainViewModel(mainViewModel);
fragmentTodayBinding.searchButton.setOnClickListener(this::onSearchClick);
});
return view;
}
@Override
public void onSearchClick(View v) {
mainViewModel.getCity();
Toast.makeText(getActivity(), "X", Toast.LENGTH_SHORT).show();
}
Button xml:
<Button
android:id="@+id/search_button"
android:onClick="@{(v)-> todayFragmentInterface.onSearchClick(v)}"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp"
android:layout_marginTop="5dp"
android:background="@drawable/ic_search_white_24dp" />
How to use it properly in fragment?
Follow this step:
1) Add this line in onCreateView
fragmentTodayBinding.fragment = this;
2) Add this line in your layout.xml
<variable name="fragment" type="yourPackage.ClassName" />
3) Edit onClick in xml with
android:onClick="@{(v)-> fragment.onSearchClick(v)}"
You can also remove:
fragmentTodayBinding.searchButton.setOnClickListener(this::onSearchClick);
I saw that you use @Override
so needs an Interface, the goal is the same, just use variable interface in the xml variable (and refer to it with package of interface), than use fragmentTodayBinding.myInterface = this;
So:
1) fragmentTodayBinding.myInterface = this;
2) <variable name="myInterface" type="yourPackage.Interface" />
3) android:onClick="@{(v)-> myInterface.onSearchClick(v)}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With