Java Examples for android.databinding.ViewDataBinding
The following java examples will help you to understand the usage of android.databinding.ViewDataBinding. These source code samples are taken from different open source projects.
Example 1
| Project: MVVMLight-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewDataBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setVariable(com.kelin.mvvmlight.zhihu.BR.viewModel, new MainViewModel(this));
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
((AppBarLayout) findViewById(R.id.appBarLayout)).addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
int height = appBarLayout.getHeight() - getSupportActionBar().getHeight() - ViewUtils.getStatusBarHeight(MainActivity.this);
int alpha = 255 * (0 - verticalOffset) / height;
collapsingToolbarLayout.setExpandedTitleColor(Color.argb(0, 255, 255, 255));
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.argb(alpha, 255, 255, 255));
}
});
CirclePageIndicator circlePageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Indicator must setViewPager after setAdapter,but data for ViewPager is load in other ViewModel
Messenger.getDefault().register(this, MainViewModel.TOKEN_UPDATE_INDICATOR, () -> circlePageIndicator.setViewPager(viewPager));
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
NewsListFragment fragment = new NewsListFragment();
getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
}Example 2
| Project: AndroidHttpCapture-master File: FilterAdpter.java View source code |
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewDataBinding listItemBinding;
if (convertView != null) {
listItemBinding = (ViewDataBinding) convertView.getTag();
} else {
listItemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_pages, parent, false);
convertView = listItemBinding.getRoot();
convertView.setTag(listItemBinding);
}
listItemBinding.setVariable(BR.pages, pageBeenList.get(position));
listItemBinding.executePendingBindings();
// listItemBinding.setButtonclick(new ButtonClick(MainActivity.this,position));
return convertView;
}Example 3
| Project: all-base-adapter-master File: DBMultypeSingleItemActivity.java View source code |
@Override public void onBindViewHolder(BaseBindingVH<ViewDataBinding> holder, int position) { super.onBindViewHolder(holder, position); //如果有特殊需求,可传入数据结构的泛型,避免强转 MulTypeSingleBean data = mDatas.get(position); //Binding类 不可避免的需要强转了 ViewDataBinding binding = holder.getBinding(); switch(data.getItemLayoutId()) { case R.layout.item_db_mul_1: ItemDbMul1Binding itemDbMul1Binding = (ItemDbMul1Binding) binding; break; case R.layout.item_db_mul_2: ItemDbMul2Binding itemDbMul2Binding = (ItemDbMul2Binding) binding; break; } }
Example 4
| Project: AndroidViewModel-master File: ViewModelHelper.java View source code |
public void performBinding(@NonNull final IView bindingView) {
// skip if already create
if (mBinding != null) {
return;
}
// get ViewModelBinding config
final ViewModelBindingConfig viewModelConfig = bindingView.getViewModelBindingConfig();
// if fragment not providing ViewModelBindingConfig, do not perform binding operations
if (viewModelConfig == null) {
return;
}
// perform Data Binding initialization
final ViewDataBinding viewDataBinding;
if (bindingView instanceof Activity) {
viewDataBinding = DataBindingUtil.setContentView(((Activity) bindingView), viewModelConfig.getLayoutResource());
} else if (bindingView instanceof Fragment) {
viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(viewModelConfig.getContext()), viewModelConfig.getLayoutResource(), null, false);
} else {
throw new IllegalArgumentException("View must be an instance of Activity or Fragment (support-v4).");
}
// bind all together
if (!viewDataBinding.setVariable(viewModelConfig.getViewModelVariableName(), getViewModel())) {
throw new IllegalArgumentException("Binding variable wasn't set successfully. Probably viewModelVariableName of your " + "ViewModelBindingConfig of " + bindingView.getClass().getSimpleName() + " doesn't match any variable in " + viewDataBinding.getClass().getSimpleName());
}
mBinding = viewDataBinding;
}Example 5
| Project: demos-master File: AnimAndCheckBoxActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_anim);
mBinding.setP(new Presenter());
mBinding.addOnRebindCallback(new OnRebindCallback() {
@Override
public boolean onPreBind(ViewDataBinding binding) {
ViewGroup viewGroup = (ViewGroup) binding.getRoot();
TransitionManager.beginDelayedTransition(viewGroup);
return super.onPreBind(binding);
}
});
}Example 6
| Project: Carbon-master File: CheckBoxRadioActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewDataBinding viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_checkbox_radio, null, false);
setContentView(viewDataBinding.getRoot());
ActivityCheckboxRadioBinding binding = (ActivityCheckboxRadioBinding) viewDataBinding;
Samples.initToolbar(this, getString(R.string.checkBoxRadioActivity_title));
binding.check.setOnClickListener( view -> binding.checkBox.setChecked(true));
binding.uncheck.setOnClickListener( view -> binding.checkBox.setChecked(false));
binding.checkBoxGroup.setOnCheckedChangeListener(( buttonView, isChecked) -> {
binding.checkBoxChild1.setChecked(isChecked);
binding.checkBoxChild2.setChecked(isChecked);
});
CheckBox.OnCheckedChangeListener listener = ( buttonView, isChecked) -> {
if (binding.checkBoxChild1.isChecked() != binding.checkBoxChild2.isChecked()) {
binding.checkBoxGroup.setChecked(CheckableDrawable.CheckedState.INDETERMINATE);
} else {
binding.checkBoxGroup.setChecked(binding.checkBoxChild1.isChecked());
}
};
binding.checkBoxChild1.setOnCheckedChangeListener(listener);
binding.checkBoxChild2.setOnCheckedChangeListener(listener);
}Example 7
| Project: android-sdk-sources-for-api-level-23-master File: ResourceBundle.java View source code |
public void validateMultiResLayouts() {
for (List<LayoutFileBundle> layoutFileBundles : mLayoutBundles.values()) {
for (LayoutFileBundle layoutFileBundle : layoutFileBundles) {
for (BindingTargetBundle target : layoutFileBundle.getBindingTargetBundles()) {
if (target.isBinder()) {
List<LayoutFileBundle> boundTo = mLayoutBundles.get(target.getIncludedLayout());
if (boundTo == null || boundTo.isEmpty()) {
L.e("There is no binding for %s", target.getIncludedLayout());
} else {
String binding = boundTo.get(0).getFullBindingClass();
target.setInterfaceType(binding);
}
}
}
}
}
for (Map.Entry<String, List<LayoutFileBundle>> bundles : mLayoutBundles.entrySet()) {
if (bundles.getValue().size() < 2) {
continue;
}
// and all variables have the same name
for (LayoutFileBundle bundle : bundles.getValue()) {
bundle.mHasVariations = true;
}
String bindingClass = validateAndGetSharedClassName(bundles.getValue());
Map<String, NameTypeLocation> variableTypes = validateAndMergeNameTypeLocations(bundles.getValue(), ErrorMessages.MULTI_CONFIG_VARIABLE_TYPE_MISMATCH, new ValidateAndFilterCallback() {
@Override
public List<NameTypeLocation> get(LayoutFileBundle bundle) {
return bundle.mVariables;
}
});
Map<String, NameTypeLocation> importTypes = validateAndMergeNameTypeLocations(bundles.getValue(), ErrorMessages.MULTI_CONFIG_IMPORT_TYPE_MISMATCH, new ValidateAndFilterCallback() {
@Override
public List<NameTypeLocation> get(LayoutFileBundle bundle) {
return bundle.mImports;
}
});
for (LayoutFileBundle bundle : bundles.getValue()) {
// now add missing ones to each to ensure they can be referenced
L.d("checking for missing variables in %s / %s", bundle.mFileName, bundle.mConfigName);
for (Map.Entry<String, NameTypeLocation> variable : variableTypes.entrySet()) {
if (!NameTypeLocation.contains(bundle.mVariables, variable.getKey())) {
bundle.mVariables.add(variable.getValue());
L.d("adding missing variable %s to %s / %s", variable.getKey(), bundle.mFileName, bundle.mConfigName);
}
}
for (Map.Entry<String, NameTypeLocation> userImport : importTypes.entrySet()) {
if (!NameTypeLocation.contains(bundle.mImports, userImport.getKey())) {
bundle.mImports.add(userImport.getValue());
L.d("adding missing import %s to %s / %s", userImport.getKey(), bundle.mFileName, bundle.mConfigName);
}
}
}
Set<String> includeBindingIds = new HashSet<String>();
Set<String> viewBindingIds = new HashSet<String>();
Map<String, String> viewTypes = new HashMap<String, String>();
Map<String, String> includes = new HashMap<String, String>();
L.d("validating ids for %s", bundles.getKey());
Set<String> conflictingIds = new HashSet<>();
for (LayoutFileBundle bundle : bundles.getValue()) {
try {
Scope.enter(bundle);
for (BindingTargetBundle target : bundle.mBindingTargetBundles) {
try {
Scope.enter(target);
L.d("checking %s %s %s", target.getId(), target.getFullClassName(), target.isBinder());
if (target.mId != null) {
if (target.isBinder()) {
if (viewBindingIds.contains(target.mId)) {
L.d("%s is conflicting", target.mId);
conflictingIds.add(target.mId);
continue;
}
includeBindingIds.add(target.mId);
} else {
if (includeBindingIds.contains(target.mId)) {
L.d("%s is conflicting", target.mId);
conflictingIds.add(target.mId);
continue;
}
viewBindingIds.add(target.mId);
}
String existingType = viewTypes.get(target.mId);
if (existingType == null) {
L.d("assigning %s as %s", target.getId(), target.getFullClassName());
viewTypes.put(target.mId, target.getFullClassName());
if (target.isBinder()) {
includes.put(target.mId, target.getIncludedLayout());
}
} else if (!existingType.equals(target.getFullClassName())) {
if (target.isBinder()) {
L.d("overriding %s as base binder", target.getId());
viewTypes.put(target.mId, "android.databinding.ViewDataBinding");
includes.put(target.mId, target.getIncludedLayout());
} else {
L.d("overriding %s as base view", target.getId());
viewTypes.put(target.mId, "android.view.View");
}
}
}
} catch (ScopedException ex) {
Scope.defer(ex);
} finally {
Scope.exit();
}
}
} finally {
Scope.exit();
}
}
if (!conflictingIds.isEmpty()) {
for (LayoutFileBundle bundle : bundles.getValue()) {
for (BindingTargetBundle target : bundle.mBindingTargetBundles) {
if (conflictingIds.contains(target.mId)) {
Scope.registerError(String.format(ErrorMessages.MULTI_CONFIG_ID_USED_AS_IMPORT, target.mId), bundle, target);
}
}
}
}
for (LayoutFileBundle bundle : bundles.getValue()) {
try {
Scope.enter(bundle);
for (Map.Entry<String, String> viewType : viewTypes.entrySet()) {
BindingTargetBundle target = bundle.getBindingTargetById(viewType.getKey());
if (target == null) {
String include = includes.get(viewType.getKey());
if (include == null) {
bundle.createBindingTarget(viewType.getKey(), viewType.getValue(), false, null, null, null);
} else {
BindingTargetBundle bindingTargetBundle = bundle.createBindingTarget(viewType.getKey(), null, false, null, null, null);
bindingTargetBundle.setIncludedLayout(includes.get(viewType.getKey()));
bindingTargetBundle.setInterfaceType(viewType.getValue());
}
} else {
L.d("setting interface type on %s (%s) as %s", target.mId, target.getFullClassName(), viewType.getValue());
target.setInterfaceType(viewType.getValue());
}
}
} catch (ScopedException ex) {
Scope.defer(ex);
} finally {
Scope.exit();
}
}
}
// assign class names to each
for (Map.Entry<String, List<LayoutFileBundle>> entry : mLayoutBundles.entrySet()) {
for (LayoutFileBundle bundle : entry.getValue()) {
final String configName;
if (bundle.hasVariations()) {
// append configuration specifiers.
final String parentFileName = bundle.mDirectory;
L.d("parent file for %s is %s", bundle.getFileName(), parentFileName);
if ("layout".equals(parentFileName)) {
configName = "";
} else {
configName = ParserHelper.toClassName(parentFileName.substring("layout-".length()));
}
} else {
configName = "";
}
bundle.mConfigName = configName;
}
}
}Example 8
| Project: VCL-Android-master File: AsyncImageLoader.java View source code |
public static void LoadAudioCover(final Callable<Bitmap> loader, final ViewDataBinding binding, final Activity activity) {
final Callbacks updater = new Callbacks() {
@Override
public Bitmap getImage() {
try {
return loader.call();
} catch (Exception ignored) {
return null;
}
}
@Override
public void updateImage(final Bitmap bitmap, View target) {
if (bitmap != null && activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
binding.setVariable(BR.cover, new BitmapDrawable(VLCApplication.getAppResources(), bitmap));
binding.executePendingBindings();
}
});
}
}
};
LoadImage(updater, null);
}Example 9
| Project: binding-collection-adapter-master File: ListViewInflationTest.java View source code |
@Test
@UiThreadTest
public void listView() {
List<String> items = Arrays.asList("one", "two", "three");
TestHelpers.ViewModel viewModel = new TestHelpers.ViewModel.Builder(items, ItemBinding.<String>of(me.tatarka.bindingcollectionadapter2.BR.item, R.layout.item)).build();
ViewDataBinding binding = DataBindingUtil.inflate(inflater, R.layout.list_view, null, false);
binding.setVariable(me.tatarka.bindingcollectionadapter2.BR.viewModel, viewModel);
binding.executePendingBindings();
ListView listView = (ListView) binding.getRoot();
@SuppressWarnings("unchecked") BindingListViewAdapter<String> adapter = (BindingListViewAdapter<String>) listView.getAdapter();
assertThat(TestHelpers.iterable(adapter)).containsExactlyElementsOf(items);
}Example 10
| Project: marvel-master File: CharacterActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewDataBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_character);
// inject views using ButterKnife
ButterKnife.bind(this);
if (null == getIntent() || null == getIntent().getExtras() || null == getIntent().getExtras().getSerializable(ARG_CHARACTER)) {
finish();
return;
}
// get args
CharacterModel character = (CharacterModel) getIntent().getExtras().getSerializable(ARG_CHARACTER);
// bind value using Android Binding
binding.setVariable(BR.character, character);
setupToolbar(character.getName());
Timber.d("Character Activity Created");
}Example 11
| Project: lavender-master File: AlbumDetailAdapter.java View source code |
@Override
public void setBingVariables(ViewDataBinding binding, int position) {
final ItemDetailBinding bd = (ItemDetailBinding) binding;
String url = Utils.convertImageUrl(bd.iv.getContext(), get(position).getUrl());
PicassoHelper.getInstance(bd.iv.getContext()).load(url).error(R.mipmap.nat_geo_480).noFade().placeholder(R.mipmap.nat_geo_480).tag(TAG_DETAIL).config(Bitmap.Config.RGB_565).into(bd.iv, new Callback() {
@Override
public void onSuccess() {
bd.iv.setOriginalSize(((BitmapDrawable) bd.iv.getDrawable()).getBitmap().getWidth(), ((BitmapDrawable) bd.iv.getDrawable()).getBitmap().getHeight());
}
@Override
public void onError() {
bd.iv.setVisibility(View.GONE);
}
});
}Example 12
| Project: BaseRecyclerViewAdapterHelper-master File: DataBindingUseAdapter.java View source code |
@Override
protected void convert(MovieViewHolder helper, Movie item) {
ViewDataBinding binding = helper.getBinding();
binding.setVariable(BR.movie, item);
binding.setVariable(BR.presenter, mPresenter);
binding.executePendingBindings();
switch(helper.getLayoutPosition() % 2) {
case 0:
helper.setImageResource(R.id.iv, R.mipmap.m_img1);
break;
case 1:
helper.setImageResource(R.id.iv, R.mipmap.m_img2);
break;
}
}Example 13
| Project: cusnews-master File: EntriesAdapter.java View source code |
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context cxt = parent.getContext();
// boolean landscape = cxt.getResources().getBoolean(R.bool.landscape);
LayoutInflater inflater = LayoutInflater.from(cxt);
if (!Prefs.getInstance().showAllImages()) {
mLayoutResId = R.layout.item_vertical_no_image_entry;
}
ViewDataBinding binding = DataBindingUtil.inflate(inflater, mLayoutResId, parent, false);
return new EntriesAdapter.ViewHolder(binding);
}Example 14
| Project: mv2m-master File: RecyclerViewDemoActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView = new RecyclerView(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
setContentView(recyclerView);
ObservableArrayList<DemoItem> items = new ObservableArrayList<>();
BindableAdapter<DemoItem> adapter = new BindableAdapter<>(items);
adapter.addViewType(new BindableAdapter.ViewHolderFactory<NormalDemoItem>() {
@Override
public BindableViewHolder<NormalDemoItem> create(ViewGroup viewGroup) {
return BindableViewHolder.create(NormalListItemBinding.inflate(getLayoutInflater(), viewGroup, false), BR.item);
}
}, NormalDemoItem.class);
adapter.addViewType(BindableViewHolder.<TitleDemoItem>factory(getLayoutInflater(), BR.item, new BindableViewHolder.BindingInflater() {
@Override
public ViewDataBinding inflate(LayoutInflater layoutInflater, ViewGroup viewGroup, boolean attachToRoot) {
return TitleListItemBinding.inflate(layoutInflater, viewGroup, attachToRoot);
}
}), TitleDemoItem.class);
recyclerView.setAdapter(adapter);
items.add(new TitleDemoItem("Title"));
items.add(new NormalDemoItem("normal1"));
items.add(new NormalDemoItem("normal2"));
items.add(new NormalDemoItem("normal3"));
items.add(new NormalDemoItem("normal4"));
items.add(new NormalDemoItem("normal5"));
}Example 15
| Project: firebase-jobdispatcher-android-master File: JobFormActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_form);
final ViewDataBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_job_form);
binding.setVariable(com.firebase.jobdispatcher.testapp.BR.form, form);
View.OnClickListener onScheduleButtonClickListener = new ScheduleButtonClickListener(form, new FirebaseJobDispatcher(new GooglePlayDriver(this)));
AppCompatButton scheduleButton = (AppCompatButton) findViewById(R.id.schedule_button);
assert scheduleButton != null;
scheduleButton.setOnClickListener(onScheduleButtonClickListener);
}Example 16
| Project: SyncthingAndroid-master File: CardRecyclerAdapter.java View source code |
@Override
public final CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View v = mLayoutInflater.inflate(viewType, parent, false);
final CardViewHolder viewHolder;
if (getBindingComponent() != null) {
viewHolder = new CardViewHolder(v, getBindingComponent());
} else {
viewHolder = new CardViewHolder(v);
}
//Trick from the databinding talk by google
viewHolder.getBinding().addOnRebindCallback(new OnRebindCallback() {
@Override
public boolean onPreBind(ViewDataBinding binding) {
return mRecyclerView != null && mRecyclerView.isComputingLayout();
}
@Override
public void onCanceled(ViewDataBinding binding) {
if (mRecyclerView == null || mRecyclerView.isComputingLayout()) {
return;
}
int position = mRecyclerView.getChildAdapterPosition(binding.getRoot());
if (position != RecyclerView.NO_POSITION) {
notifyItemChanged(position, DATA_INVALIDATION);
}
}
});
return viewHolder;
}Example 17
| Project: android-ui-toolkit-demos-master File: ListBindingAdapters.java View source code |
/*
@BindingAdapter({"entries", "layout"})
public static <T> void setEntries(ViewGroup viewGroup,
Object oldEntries, int oldLayoutId,
Object newEntries, int newLayoutId) {
if (oldEntries == newEntries && oldLayoutId == newLayoutId) {
return; // nothing has changed
}
EntryChangeListener listener =
ListenerUtil.getListener(viewGroup, R.id.entryListener);
if (oldEntries != newEntries && listener != null && oldEntries instanceof ObservableList) {
((ObservableList)oldEntries).removeOnListChangedCallback(listener);
}
if (newEntries == null) {
viewGroup.removeAllViews();
} else {
if (newEntries instanceof ObservableList) {
if (listener == null) {
listener =
new EntryChangeListener(viewGroup, newLayoutId);
ListenerUtil.trackListener(viewGroup, listener,
R.id.entryListener);
} else {
listener.setLayoutId(newLayoutId);
}
if (newEntries != oldEntries) {
((ObservableList)newEntries).addOnListChangedCallback(listener);
}
}
resetViews(viewGroup, newLayoutId, (List) newEntries);
}
}
*/
/**
* Inflates and binds a layout to an entry to the {@code data} variable
* of the bound layout.
*
* @param inflater The LayoutInflater
* @param parent The ViewGroup containing the list of Views
* @param layoutId The layout ID to use for the list item
* @param entry The data to bind to the inflated View
* @return A ViewDataBinding, bound to a newly-inflated View with {@code entry}
* set as the {@code data} variable.
*/
private static ViewDataBinding bindLayout(LayoutInflater inflater, ViewGroup parent, int layoutId, Object entry) {
ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
if (!binding.setVariable(BR.data, entry)) {
String layoutName = parent.getResources().getResourceEntryName(layoutId);
Log.w(TAG, "There is no variable 'data' in layout " + layoutName);
}
return binding;
}Example 18
| Project: epoxy-master File: GeneratedModelWriter.java View source code |
/**
* Add `setDataBindingVariables` for DataBinding models if they haven't implemented it. This adds
* the basic method and a method that checks for payload changes and only sets the variables that
* changed.
*/
private Iterable<MethodSpec> generateDataBindingMethodsIfNeeded(GeneratedModelInfo info) {
if (!isDataBindingModel(info.getSuperClassElement())) {
return Collections.emptyList();
}
MethodSpec bindVariablesMethod = MethodSpec.methodBuilder("setDataBindingVariables").addAnnotation(Override.class).addParameter(ClassName.get("android.databinding", "ViewDataBinding"), "binding").addModifiers(Modifier.PROTECTED).returns(TypeName.VOID).build();
// If the base method is already implemented don't bother checking for the payload method
if (implementsMethod(info.getSuperClassElement(), bindVariablesMethod, typeUtils)) {
return Collections.emptyList();
}
ClassName generatedModelClass = info.getGeneratedName();
String moduleName = dataBindingModuleLookup.getModuleName(info.getSuperClassElement());
Builder baseMethodBuilder = bindVariablesMethod.toBuilder();
Builder payloadMethodBuilder = bindVariablesMethod.toBuilder().addParameter(getClassName(UNTYPED_EPOXY_MODEL_TYPE), "previousModel").beginControlFlow("if (!(previousModel instanceof $T))", generatedModelClass).addStatement("setDataBindingVariables(binding)").addStatement("return").endControlFlow().addStatement("$T that = ($T) previousModel", generatedModelClass, generatedModelClass);
ClassName brClass = ClassName.get(moduleName, "BR");
boolean validateAttributes = configManager.shouldValidateModelUsage();
for (AttributeInfo attribute : info.getAttributeInfo()) {
String attrName = attribute.getName();
CodeBlock setVariableBlock = CodeBlock.of("binding.setVariable($T.$L, $L)", brClass, attrName, attribute.getterCode());
if (validateAttributes) {
// The setVariable method returns false if the variable id was not found in the layout.
// We can warn the user about this if they have model validations turned on, otherwise
// it fails silently.
baseMethodBuilder.beginControlFlow("if (!$L)", setVariableBlock).addStatement("throw new $T(\"The attribute $L was defined in your data binding model ($L) but " + "a data variable of that name was not found in the layout.\")", IllegalStateException.class, attrName, info.getSuperClassName()).endControlFlow();
} else {
baseMethodBuilder.addStatement("$L", setVariableBlock);
}
// Handle binding variables only if they changed
startNotEqualsControlFlow(payloadMethodBuilder, attribute).addStatement("$L", setVariableBlock).endControlFlow();
}
ArrayList<MethodSpec> methods = new ArrayList<>();
methods.add(baseMethodBuilder.build());
methods.add(payloadMethodBuilder.build());
return methods;
}Example 19
| Project: agera-master File: DataBindingRepositoryPresenterCompiler.java View source code |
@Override
public void bind(@NonNull final Object data, final int index, @NonNull final RecyclerView.ViewHolder holder) {
final Object item = getItems(data).get(index);
final View view = holder.itemView;
final ViewDataBinding viewDataBinding = DataBindingUtil.bind(view);
final Integer itemVariable = itemId.apply(item);
if (itemVariable != BR_NO_ID) {
viewDataBinding.setVariable(itemVariable, item);
view.setTag(R.id.agera__rvdatabinding__item_id, itemVariable);
}
if (collectionId != BR_NO_ID) {
viewDataBinding.setVariable(collectionId, data);
view.setTag(R.id.agera__rvdatabinding__collection_id, collectionId);
}
for (int i = 0; i < handlers.size(); i++) {
final int variableId = handlers.keyAt(i);
viewDataBinding.setVariable(variableId, handlers.valueAt(i));
}
viewDataBinding.executePendingBindings();
}Example 20
| Project: droidkaigi2016-master File: SearchPlacesAndCategoriesView.java View source code |
@Override
public BindingHolder<ViewDataBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
switch(viewType) {
case TYPE_CATEGORY:
return new BindingHolder<>(getContext(), parent, R.layout.item_search_category);
case TYPE_PLACE:
return new BindingHolder<>(getContext(), parent, R.layout.item_search_place);
case TYPE_TITLE:
return new BindingHolder<>(getContext(), parent, R.layout.item_search_title);
default:
throw new InvalidStatementException("ViewType is invalid: " + viewType);
}
}Example 21
| Project: artcodes-android-master File: ExperienceGroupAdapter.java View source code |
@Override
public void bind(final int position, final ViewDataBinding binding) {
Object item = getItemAt(position);
if (binding instanceof ExperienceCardBinding && item instanceof Experience) {
final Experience experience = (Experience) item;
final ExperienceCardBinding experienceCardBinding = (ExperienceCardBinding) binding;
experienceCardBinding.setExperience((Experience) item);
experienceCardBinding.getRoot().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ExperienceActivity.start(context, experience);
}
});
experienceCardBinding.scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArtcodeActivity.start(context, experience);
}
});
} else if (binding instanceof GroupHeaderBinding && item instanceof Group) {
Group group = ((Group) item);
((GroupHeaderBinding) binding).title.setText(getStringResourceByName(context, group.name));
if (group.showMore()) {
binding.getRoot().setOnClickListener(group.clickListener);
((GroupHeaderBinding) binding).moreButton.setOnClickListener(group.clickListener);
((GroupHeaderBinding) binding).moreButton.setVisibility(View.VISIBLE);
} else {
binding.getRoot().setOnClickListener(null);
((GroupHeaderBinding) binding).moreButton.setVisibility(View.INVISIBLE);
}
}
}Example 22
| Project: life-master File: BaseBindingFragment.java View source code |
/**
* on casting root binding
*
* @param rootBinding rootBinding
*/
@Override
protected void onCastingRootBinding(@Nullable ViewDataBinding rootBinding) {
if (rootBinding != null) {
this.castToBaseMVVMBinding(rootBinding);
} else {
// reset content view, because auto == false
this.rootBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_base_mvvm, container, false);
this.castToBaseMVVMBinding(this.rootBinding);
}
}Example 23
| Project: groupie-master File: DummyItem.java View source code |
@Override
public void bind(ViewDataBinding viewBinding, int position) {
}Example 24
| Project: MultiItem-master File: DataBindItemInput.java View source code |
@Override
protected void initInputView(BaseViewHolder holder) {
ViewDataBinding dataBinding = DataBindingUtil.getBinding(holder.itemView);
initInputView(dataBinding);
}Example 25
| Project: kickmaterial-master File: CategoriesRecyclerViewAdapter.java View source code |
public void onBindBinding(ViewDataBinding binding, int bindingVariable, int layoutRes, int position, T item) {
binding.setVariable(BR.categoryClickListener, categoryClickListener);
super.onBindBinding(binding, bindingVariable, layoutRes, position, item);
}Example 26
| Project: Idaily-master File: StoryAdapter.java View source code |
public static StoryViewHolder createViewHolder(ViewDataBinding binding) {
return new StoryViewHolder(binding.getRoot(), binding);
}Example 27
| Project: AndroidAgeraTutorial-master File: GirlListAdapter.java View source code |
@Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final GirlInfo info = getItem(position);
if (holder instanceof ViewHolder) {
ViewDataBinding binding = ((ViewHolder) holder).getBinding();
binding.setVariable(BR.info, info);
binding.executePendingBindings();
}
}Example 28
| Project: multi-type-adapter-master File: MultiTypeAdapter.java View source code |
static ItemViewHolder create(ViewGroup parent, int viewType) {
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), viewType, parent, false);
return new ItemViewHolder(binding);
}Example 29
| Project: android-data-binding-recyclerview-master File: BindingRecyclerViewAdapter.java View source code |
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int layoutId) {
if (inflater == null) {
inflater = LayoutInflater.from(viewGroup.getContext());
}
ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutId, viewGroup, false);
return new ViewHolder(binding);
}