Forked from killvetrov/BaseViewBindingFragment.java
Created
November 12, 2020 17:47
-
-
Save ricardopereira/598c637cc26c7b00d3a3c35d0f948db1 to your computer and use it in GitHub Desktop.
Android View Binding: base class to reduce boilerplate in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class BaseViewBindingFragment extends Fragment { | |
private Field bindingField; | |
private Method inflate; | |
{ | |
try { | |
for (Field declaredField : this.getClass().getDeclaredFields()) { | |
if (ViewBinding.class.isAssignableFrom(declaredField.getType())) { | |
bindingField = declaredField; | |
bindingField.setAccessible(true); | |
for (Method method : bindingField.getType().getMethods()) { | |
if (method.getParameterTypes().length == 3) { | |
inflateMethod = method; | |
break; | |
} | |
} | |
break; | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
@Nullable | |
@Override | |
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, | |
@Nullable Bundle savedInstanceState) { | |
try { | |
ViewBinding binding = (ViewBinding) inflate.invoke(null, inflater, container, false); | |
bindingField.set(this, binding); | |
return binding.getRoot(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return super.onCreateView(inflater, container, savedInstanceState); | |
} | |
@Override | |
public void onDestroyView() { | |
try { | |
bindingField.set(this, null); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
super.onDestroyView(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExampleFragment extends BaseViewBindingFragment { | |
// Just one declaration and it's done | |
private FragmentExampleBinding binding; | |
@Override | |
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { | |
binding.textView.setText("..."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment