Skip to content

Instantly share code, notes, and snippets.

@killvetrov
Created March 30, 2021 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killvetrov/793d25b9c5232d4a487e38d3f24a650a to your computer and use it in GitHub Desktop.
Save killvetrov/793d25b9c5232d4a487e38d3f24a650a to your computer and use it in GitHub Desktop.
public class ExampleFragment extends Fragment {
private FragmentExampleBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState) {
return ViewBindingDelegate.inflate(
FragmentExampleBinding::inflate, b -> binding = b,
inflater, container, getViewLifecycleOwner());
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// binding is assigned in onCreateView and will be set to null as soon as view lifecycle will reach DESTROYED state
binding.textView.setText("...");
}
}
package viewbindingdelegate;
// Analog of java.util.function.Function and .BiFunction for 3 arguments
public interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
package viewbindingdelegate;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.util.Consumer;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.viewbinding.ViewBinding;
public class ViewBindingDelegate<VB extends ViewBinding> implements DefaultLifecycleObserver {
private final Consumer<VB> viewBindingVarSetter;
@NonNull
public static <VB extends ViewBinding> View inflate(
@NonNull TriFunction<LayoutInflater, ViewGroup, Boolean, VB> viewBindingInflateMethod,
@NonNull Consumer<VB> viewBindingVarSetter,
@NonNull LayoutInflater inflater, ViewGroup container,
@NonNull LifecycleOwner lifecycleOwner
) {
ViewBindingDelegate<VB> delegate = new ViewBindingDelegate<>(viewBindingVarSetter);
VB viewBinding = viewBindingInflateMethod.apply(inflater, container, false);
viewBindingVarSetter.accept(viewBinding);
lifecycleOwner.getLifecycle().addObserver(delegate);
return viewBinding.getRoot();
}
private ViewBindingDelegate(Consumer<VB> viewBindingVarSetter) {
this.viewBindingVarSetter = viewBindingVarSetter;
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
owner.getLifecycle().removeObserver(this);
viewBindingVarSetter.accept(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment