Skip to content

Instantly share code, notes, and snippets.

@Palatis
Last active September 10, 2021 16:07
Show Gist options
  • Save Palatis/027561fff68c9dee326496e9a9e7c768 to your computer and use it in GitHub Desktop.
Save Palatis/027561fff68c9dee326496e9a9e7c768 to your computer and use it in GitHub Desktop.
generic android DataBinding Fragment super class
public class BindingFragment<BindingT extends ViewDataBinding> extends Fragment {
private BindingT mBinding = null;
private boolean mSuperCalled = false;
protected BindingT getBinding() {
return mBinding;
}
@Nullable
@Override
public final View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
try {
@SuppressWarnings("unchecked") final Method inflateMethod = ((Class<BindingT>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0])
.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
//noinspection unchecked
mBinding = (BindingT) inflateMethod.invoke(null, inflater, container, false);
mSuperCalled = false;
onBindingInflated(mBinding);
if (!mSuperCalled)
throw new IllegalStateException("onBindingInflated() didn't call super");
return mBinding.getRoot();
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
FirebaseCrash.log("Something really bad happened!");
FirebaseCrash.report(ex);
}
return null;
}
@CallSuper
protected void onBindingInflated(BindingT binding) {
mSuperCalled = true;
}
@Override
public void onDestroyView() {
mBinding = null;
super.onDestroyView();
}
}
# BindingFragment
-keep class ** extends android.databinding.ViewDataBinding {
public static ** inflate( android.view.LayoutInflater, android.view.ViewGroup, boolean);
}
public OtherFragment extends BindingFragment<FragmentSomeBinding> {
private SomeClass mSomeVar = new SomeClass();
@Override
protected void onBindingInflated(final FragmentSomeBinding binding) {
super.onBindingInflated(binding);
binding.setFragment(this);
binding.setSomeVar(mSomeVar);
}
public void onSomethignClicked(View view) {
getBinding().something.setVisibility(View.VISIBLE);
}
}
@Palatis
Copy link
Author

Palatis commented Sep 10, 2021

What if we want to extend OtherFragment with a new binding class?

just do so and call super.onBindingInflated() in your derived class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment