I want to use data binding in a fragment to trigger all my button clicks in handler class. When I run the code below I get the following error.
D:CodingupdatedGithubAndroidHiveDataBindingFragmentsappbuildgeneratedap_generated_sourcesdebugoutcomexampleandroidhivedatabindingfragmentsDataBinderMapperImpl.java:10: error: cannot find symbol import com.example.androidhivedatabindingfragments.databinding.FragmentUserBindingImpl; ^ symbol: class FragmentUserBindingImpl location: package com.example.androidhivedatabindingfragments.databinding
I’m not sure if the problem is with how I’m passing the context to the Handler class or if I’ve done some wrong the Data binding.
UserFragment
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { FragmentUserBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user, container, false); View view = binding.getRoot(); User user = new User(); user.setName("First Last"); user.setEmail("email@email.com"); binding.setUser(user); MyClickHandlers handlers = new MyClickHandlers(getActivity()); binding.setHandlers(handlers); return view; }
MyClickHandlers
public class MyClickHandlers { private static final String TAG = "MyClickHandlers"; Context context; public MyClickHandlers(Context context) { this.context = context; } public void myClick() { Log.d(TAG, "myClick: "); } }
fragment_user
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:bind="http://schemas.android.com/apk/res-auto"> <data> <variable name="user" type="com.example.androidhivedatabindingfragments.User" /> <variable name="handlers" type="com.example.androidhivedatabindingfragments.MyClickHandlers" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".UserFragment" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click ME" android:id="@+id/btn_Click" android:onClick="@{handlers::myClick}"/> <include android:id="@+id/content" layout="@layout/content_main" bind:user="@{user}" /> </LinearLayout> </layout>
Advertisement
Answer
Your onClick()
of MyHandlers
has to have the view you click as a parameter, so change it to be:
public void myClick(View view) { Log.d(TAG, "myClick: "); }
I guess that will solve the problem, also please instantiate the MyClickHandlers
with the context instead of activity, as both are different things.
so in onCreateView()
, add requireContext()
instead of getActivity()
MyClickHandlers handlers = new MyClickHandlers(requireContext());