Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onClick in fragment in data binding?

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?

like image 715
user9897182 Avatar asked Jan 22 '19 12:01

user9897182


Video Answer


1 Answers

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)}"

like image 146
Michele Lacorte Avatar answered Oct 21 '22 17:10

Michele Lacorte