Last active
October 13, 2017 09:28
-
-
Save blipinsk/c656f48b6eeb0903e41f3c85a34f95a2 to your computer and use it in GitHub Desktop.
The easiest way to use ViewDataBinding with RecyclerView.ViewHolder
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
/* | |
* Copyright 2017 Bartosz Lipinski | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
public class BindingViewHolder<BINDING extends ViewDataBinding> extends RecyclerView.ViewHolder { | |
private final BINDING binding; | |
public final BINDING binding() { | |
return binding; | |
} | |
protected BindingViewHolder(BINDING binding) { | |
super(binding.getRoot()); | |
this.binding = binding; | |
} | |
public static <T extends ViewDataBinding> BindingViewHolder<T> with(T binding) { | |
return new BindingViewHolder<>(binding); | |
} | |
public static Inflater withLayout(@LayoutRes int layoutRes) { | |
return new Inflater(layoutRes); | |
} | |
public static <T extends ViewDataBinding> T inflateBinding(@LayoutRes int layoutRes, | |
ViewGroup container) { | |
return DataBindingUtil.inflate(LayoutInflater.from(container.getContext()), | |
layoutRes, container, false); | |
} | |
public final static class Inflater { | |
private final int layoutRes; | |
Inflater(@LayoutRes int layoutRes) { | |
this.layoutRes = layoutRes; | |
} | |
@SuppressWarnings("unchecked") | |
public final <T extends ViewDataBinding> BindingViewHolder<T> inflatedIn(ViewGroup container) { | |
if (container == null) { | |
throw new NullPointerException("container == null"); | |
} | |
return (BindingViewHolder<T>) with(inflateBinding(layoutRes, container)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment