@BindingAdapter({"checked", "model"}) public static <T> void setChecked(RadioButton radioButton, final ObservableField<T> checked, final T model) { if (checked == null) { return; } radioButton.setOnCheckedChangeListener( (buttonView, isChecked) -> { if ((checked.get() == null || !checked.get().equals(model)) && isChecked) { checked.set(model); } }); final T checkedModel = checked.get(); final boolean shouldBeChecked = checkedModel != null && checkedModel.equals(model); if (shouldBeChecked != radioButton.isChecked()) { radioButton.setChecked(shouldBeChecked); } }
@BindingAdapter("model") public static void bindToModel(DiscreteSeekBar seekBar, final SeekBarModel model) { DiscreteSeekBar.NumericTransformer transformer = seekBar.getNumericTransformer(); if (!(transformer instanceof NumericTransformer)) { transformer = new NumericTransformer(); seekBar.setNumericTransformer(transformer); } final NumericTransformer customTransformer = (NumericTransformer) transformer; customTransformer.setValues(model.getMinValue(), model.getMaxValue()); seekBar.setMin(0); seekBar.setMax(100); final int percentage = (int) customTransformer.transformToPercentage(model.getValue().get()); // Bug in the library seekBar.setProgress(1); seekBar.setProgress(percentage); seekBar.setOnProgressChangeListener( SimpleOnProgressChangeListener.forStopTrackingTouch(seekBar1 -> { model.getValue().set(customTransformer.transformFromPercentage(seekBar.getProgress())); })); }
@BindingAdapter("elevation") public static void elevationBoolean(View view, boolean elevation) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && elevation) { view.setElevation(view.getContext().getResources().getInteger(R.integer.common_elevation)); } else { jLogger.w("Sorry, the system version of the device is under API 21, elevation will take no effect."); } }
@BindingAdapter("android:visibility") public static void setVisibility(View view, int visibility) { switch (visibility) { case 0: view.setVisibility(View.VISIBLE); break; case 4: view.setVisibility(View.INVISIBLE); break; case 8: view.setVisibility(View.GONE); break; default: view.setVisibility(View.GONE); break; } }
@BindingAdapter({"bind:items"}) public static void populateDiagram(LineChart view, List<SingleValue> items) { if (null == items || items.size() == 0) { return; } List<Entry> entries = new ArrayList<>(); for (int i = 0; i < items.size(); i++) { final SingleValue item = items.get(i); final Entry entry = new Entry(i, (float) item.getValue(), item); entries.add(entry); } LineDataSet dataSet = new LineDataSet(entries, view.getContext().getString(R.string.currency_value)); LineData lineData = new LineData(dataSet); formatXAxisLabels(view, items); view.setData(lineData); view.invalidate(); }
@BindingAdapter({"imageAddress"}) public static void loadImage(final ImageView imageView, final String imageAddress) { if (imageAddress != null && imageAddress.startsWith("https://s3.amazonaws.com/bikedeboa/")) { Context context = imageView.getContext(); // Hopefully the thumbnail is already disk cached and no requests are made DrawableRequestBuilder<String> thumbnailRequest = Glide .with(context) .load(imageAddress.replace("images/", "images/thumbs/")) .diskCacheStrategy(DiskCacheStrategy.ALL) .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .transform(new BlurTransformation(context)); Glide.with(context) .load(imageAddress) .thumbnail(thumbnailRequest) .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .priority(Priority.HIGH) .into(imageView); } }
/** * (伪)双向 databinding: 同 {@link RecyclerViewAdapter#setDataTwoWay(RecyclerView, ListVM, List)} * * @param container * @param vm * @param datas * @param <T> */ @BindingAdapter({"vm", "data"}) public static <T> void setDataTwoWay(final ViewGroup container, final ListVM<T> vm, List<T> datas){ if(vm == null){ return ; } bind(container, vm, datas); if(vm instanceof TwoWayListVM){ boolean isInited = container.getTag(R.id.db_inited) != null; if(!isInited) { container.setTag(R.id.db_inited, true); loadData(container, (TwoWayListVM<T>)vm, null, null); } } }
/** * Facilitates binding editor action listeners on EditText fields. */ @BindingAdapter("onEditorAction") public static void setOnEditorActionListener( EditText layout, TextView.OnEditorActionListener listener) { layout.setOnEditorActionListener(listener); }
@BindingAdapter("circleImageUrl") public static void setCircleImage(CircleImageView view, String url) { Glide.with(view.getContext()).load(url) .crossFade(800) .dontAnimate() .placeholder(R.drawable.cross_image) .error(R.drawable.close_press) .into(view); /*Glide.with(view.getContext()).load(url) .asBitmap() .placeholder(R.drawable.cross_image) .error(R.drawable.close_press) .into(new BitmapImageViewTarget(view) { @Override protected void setResource(Bitmap resource) { super.setResource(resource); RoundedBitmapDrawable circleImage = RoundedBitmapDrawableFactory.create(view.getResources(), resource); circleImage.setCircular(true); view.setImageDrawable(circleImage); } });*/ }
@BindingAdapter(value = {"imageUrl", "defaultImg", "radius"}, requireAll = false) public static void setImage(ImageView imageView, String imageUrl, Drawable defaultImg, int radius) { DrawableRequestBuilder drawableTypeRequest = Glide.with(imageView.getContext()).load(imageUrl).crossFade(); if (defaultImg != null) { drawableTypeRequest.placeholder(defaultImg).error(defaultImg); } else { drawableTypeRequest.placeholder(R.drawable.bg_defautl_imageview).error(R.drawable.bg_defautl_imageview); } if (radius > 0) { drawableTypeRequest.bitmapTransform(new CenterCrop(imageView.getContext()), new RoundedCornersTransformation(imageView.getContext(), PixelUtil.dp2px(radius), 0)); } else { drawableTypeRequest.bitmapTransform(new CenterCrop(imageView.getContext())); } drawableTypeRequest.into(imageView); }
/** * 电影详情页显示电影图片(等待被替换)(测试的还在,已可以弃用) * 没有加载中的图 */ @BindingAdapter("android:showImg") public static void showImg(ImageView imageView, String url) { Glide.with(imageView.getContext()) .load(url) .crossFade(500) .error(getDefaultPic(0)) .into(imageView); }
/** * 书籍列表图片 */ @BindingAdapter("android:showBookImg") public static void showBookImg(ImageView imageView, String url) { Glide.with(imageView.getContext()) .load(url) .crossFade(500) .override((int) CommonUtils.getDimens(R.dimen.book_detail_width), (int) CommonUtils.getDimens(R.dimen.book_detail_height)) .placeholder(getDefaultPic(2)) .error(getDefaultPic(2)) .into(imageView); }
@BindingAdapter("src") public static void setImageSrc(ImageView view, File file) { if (file != null) { Glide.with(view).load(file).into(view); } else { Glide.with(view).clear(view); } }
@BindingAdapter(value = {"validateMinLength", "validateMinLengthMessage", "validateMinLengthAutoDismiss"}, requireAll = false) public static void bindingMinLength(TextView view, int minLength, String errorMessage, boolean autoDismiss) { if (autoDismiss) { EditTextHandler.disableErrorOnChanged(view); } String handledErrorMessage = ErrorMessageHelper.getStringOrDefault(view, errorMessage, R.string.error_message_min_length, minLength); ViewTagHelper.appendValue(R.id.validator_rule, view, new MinLengthRule(view, minLength, handledErrorMessage)); }
@BindingAdapter("containerMargin") public static void setContainerMargin(View view, boolean isTopLevelComment) { if (view.getTag() == null) { view.setTag(true); ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); float horizontalMargin = view.getContext().getResources().getDimension(R.dimen.activity_horizontal_margin); float topMargin = isTopLevelComment ? view.getContext().getResources().getDimension(R.dimen.activity_vertical_margin) : 0; layoutParams.setMargins((int) horizontalMargin, (int) topMargin, (int) horizontalMargin, 0); view.setLayoutParams(layoutParams); } }
@BindingAdapter("imageLoadRounded") public static void setImageLoadRounded(final ImageView imageView, String urlImage){ if (!TextUtils.isEmpty(urlImage)) { Glide.with(imageView.getContext()).load(urlImage).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(imageView.getContext().getResources(), resource); circularBitmapDrawable.setCircular(true); imageView.setImageDrawable(circularBitmapDrawable); } }); } }
@BindingAdapter({"imageUrl"}) public static void loadImg(ImageView v, String url) { v.setColorFilter(v.getContext().getResources().getColor(SpUtil.isNight() ? R.color.CoverColor : R.color.colorWhite), PorterDuff.Mode.MULTIPLY); Glide.with(v.getContext()) .load(getFuckUrl(url)) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(v); }
@BindingAdapter(value = {"items", "viewProvider"}, requireAll = true) public static <TModel, TView extends View & IDataViewModelProvider<TModel>> void setItems(RecyclerView recyclerView, ObservableArrayList<TModel> items, RecyclerViewProvider<TModel, TView> viewProvider) { if (recyclerView.getAdapter() != null && recyclerView.getAdapter() instanceof RecyclerViewListAdapter && ((RecyclerViewListAdapter)recyclerView.getAdapter()).getList() == items) return; RecyclerViewListAdapter<TModel, TView> adapter = new RecyclerViewListAdapter<>(items, viewProvider); recyclerView.setAdapter(adapter); }
@BindingAdapter({"article"}) public static void setArticle(TextView tv, String url) { if (TextUtils.isEmpty(url)) return; String article = url.replace("<br>", "\n").replaceAll(" ", "").replaceAll("//", ""); if (!TextUtils.isEmpty(article) && article.indexOf(">") > 0) { article = article.substring(article.indexOf(">") + 4, article.length()); } tv.setText(article); }
@BindingAdapter(value = {"imageUrl", "placeHolder", "error"}, requireAll = false) /** * 不支持mipmap下的图片 */ public static void loadImage(ImageView imageView, String url, Drawable holderDrawable, Drawable errorDrawable) { Glide.with(imageView.getContext()) .load(url) .apply(GlideRequestOption.getRequestOptions().placeholder(holderDrawable) .error(errorDrawable)) .into(imageView); }
@BindingAdapter("selectedItems") public static <T> void setSelectedItems( AtomListView view, @Nullable ObservableList<T> list){ if(view.getSelectedItems() == list) return; view.setSelectedItems(list); }
@SuppressWarnings("unchecked") @BindingAdapter(value = {"bindingItem", "items", "adapter", "itemIds", "viewHolder"}, requireAll = false) public static <T> void setAdapter(RecyclerView recyclerView, BindingItem<T> bindingItem, List<T> items, MvvmAdapter<T> adapter, MvvmAdapter.ItemIds<? super T> itemIds, MvvmAdapter.ViewHolderFactory viewHolderFactory) { if (bindingItem == null) { throw new IllegalArgumentException("bindingItem must not be null"); } MvvmAdapter oldAdapter = (MvvmAdapter) recyclerView.getAdapter(); if (adapter == null) { if (oldAdapter == null) { adapter = new MvvmAdapter<>(); } else { adapter = oldAdapter; } } adapter.setBindingItem(bindingItem); adapter.setItems(items); adapter.setItemIds(itemIds); adapter.setViewHolderFactory(viewHolderFactory); if (oldAdapter != adapter) { recyclerView.setAdapter(adapter); } }
@BindingAdapter(value = "resource") public static void setResource(RecyclerView recyclerView, Resource resource){ RecyclerView.Adapter adapter = recyclerView.getAdapter(); if(adapter == null) return; if(resource == null || resource.data == null) return; if(adapter instanceof BaseAdapter){ ((BaseAdapter)adapter).setData((List) resource.data); } }
@BindingAdapter(value = {"validateRegex", "validateRegexMessage", "validateRegexAutoDismiss"}, requireAll = false) public static void bindingRegex(TextView view, String pattern, String errorMessage, boolean autoDismiss) { if (autoDismiss) { EditTextHandler.disableErrorOnChanged(view); } String handledErrorMessage = ErrorMessageHelper.getStringOrDefault(view, errorMessage, R.string.error_message_regex_validation); ViewTagHelper.appendValue(R.id.validator_rule, view, new RegexRule(view, pattern, handledErrorMessage)); }
@BindingAdapter(value = {"validatePassword", "validatePasswordMessage", "validatePasswordAutoDismiss"}, requireAll = false) public static void bindingPassword(TextView view, TextView comparableView, String errorMessage, boolean autoDismiss) { if (autoDismiss) { EditTextHandler.disableErrorOnChanged(view); } String handledErrorMessage = ErrorMessageHelper.getStringOrDefault(view, errorMessage, R.string.error_message_not_equal_password); ViewTagHelper.appendValue(R.id.validator_rule, view, new ConfirmPasswordRule(view, comparableView, handledErrorMessage)); }
@BindingAdapter({"app:imageUrl", "app:placeholder"}) public static void loadImage(final ImageView view, final String url, final Drawable placeholder) { Picasso.with(view.getContext()) .load(url) .placeholder(placeholder) .into(view); }
@BindingAdapter("android:src") public static void setSrc(ImageView view, Bitmap bitmap) { view.setImageBitmap(bitmap); }
/** * Facilitates loading images into an ImageView using Glide, by binding a string URI. */ @BindingAdapter("android:src") public static void setImageUri(ImageView view, String imageUri) { GlideApp.with(view) .load(imageUri) .fitCenter() .into(view); }
@BindingAdapter(value = {"fragments", "curIndex"}, requireAll = false) public static void bind(ViewPager container, final List<? extends Fragment> fragments, int curIndex) { if(!(container.getContext() instanceof FragmentActivity)) throw new IllegalArgumentException(TAG + "context must instanceof FragmentActivity"); FragmentManager fm = ((FragmentActivity) container.getContext()).getSupportFragmentManager(); if (fragments != null && !fragments.isEmpty()) { PagerAdapter adapter = container.getAdapter(); if(adapter == null) { // initialize, fragments are only added once !!! container.setAdapter(adapter = new FragmentPagerAdapter(fm) { @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }); } adapter.notifyDataSetChanged(); if(curIndex >= 0 && curIndex < fragments.size()) container.setCurrentItem(curIndex); } }
/** * (伪)双向 databinding: 自动调用 {@link TwoWayListVM#getLoadTask()}, * 并自动触发 {@link TwoWayListVM#setData(ObservableArrayList)} * 然后自动更新 RecyclerView * * @param container * @param vm * @param datas * @param <T> */ @BindingAdapter({"vm", "data"}) public static <T> void setDataTwoWay(final RecyclerView container, final ListVM<T> vm, List<T> datas){ if(vm == null){ return ; } setData(container, vm, datas); if(vm instanceof TwoWayListVM) { boolean isInited = container.getTag(R.id.db_inited) != null; if (!isInited) { container.setTag(R.id.db_inited, true); final TwoWayListVM<T> _vm = ((TwoWayListVM<T>) vm); loadData(container, _vm, null, null); // 若 parent 可下拉刷新,设置回调 ViewParent parent = container.getParent(); if (parent != null && parent instanceof TwoWayListVM.Refreshable) { final TwoWayListVM.Refreshable refreshable = (TwoWayListVM.Refreshable) parent; ((TwoWayListVM.Refreshable) parent).setOnRefresh(new TwoWayListVM.Refreshable.CallBack() { @Override public void onRefresh() { loadData(container, _vm, null, refreshable); } @Override public void onLoadMore() { List<T> data = _vm.getData(); if (data.size() - 1 >= 0) { loadData(container, _vm, data.get(data.size() - 1), refreshable); } } }); } } } }
@BindingAdapter(value = {"validateType", "validateTypeMessage", "validateTypeAutoDismiss"}, requireAll = false) public static void bindingTypeValidation(TextView view, String fieldTypeText, String errorMessage, boolean autoDismiss) { if (autoDismiss) { EditTextHandler.disableErrorOnChanged(view); } TypeRule.FieldType fieldType = getFieldTypeByText(fieldTypeText); try { String handledErrorMessage = ErrorMessageHelper.getStringOrDefault(view, errorMessage, fieldType.errorMessageId); ViewTagHelper.appendValue(R.id.validator_rule, view, fieldType.instantiate(view, handledErrorMessage)); } catch (Exception ignored) {} }
@BindingAdapter("imageUrl") public static void setImage(ImageView view, String url) { Glide.with(view.getContext()).load(url) .crossFade(800) .placeholder(R.drawable.cross_image) .error(R.drawable.cross_image) .into(view); }
@BindingAdapter(value = "url") public static void loadImageUrl(ImageView view, String url) { if (url != null && !url.equals("")) Picasso.with(view.getContext()) .load(url) .into(view); }
@BindingAdapter(value = {"itemBinding", "items", "adapter", "itemIds", "viewHolder", "onItemBound"}, requireAll = false) public static <T> void setAdapter(RecyclerView recyclerView, OnItemBind<T> onItemBind, List<T> items, BindingRecyclerViewAdapter<T> adapter, BindingRecyclerViewAdapter.ItemIds<? super T> itemIds, BindingRecyclerViewAdapter.ViewHolderFactory viewHolderFactory, OnItemBoundHandler<T> onItemBoundHandler) { ItemBinding<T> itemBinding = ((onItemBind != null) && (onItemBoundHandler != null)) ? ItemBinding.of(new OnItemBindWrapper<>(onItemBind, onItemBoundHandler)) : ItemBinding.of(onItemBind); BindingRecyclerViewAdapters.setAdapter(recyclerView, itemBinding, items, adapter, itemIds, viewHolderFactory); }
@BindingAdapter("judgehint") public static void setHint(EditText view, CharSequence hint) { switch (view.getId()) { case R.id.edit_options_logcat: String options = "[options]"; if (!hint.equals("")) { options = hint.toString(); } view.setHint(options); break; case R.id.edit_filter_logcat: String filter = "[filterspecs]"; if (!hint.equals("")) { filter = hint.toString(); } view.setHint(filter); break; case R.id.edit_grep_logcat: String grep = "[grep]"; if (!hint.equals("")) { grep = hint.toString(); } view.setHint(grep); break; default: ZLog.e("no match"); break; } }
@BindingAdapter(value = {"validateDate", "validateDateMessage", "validateDateAutoDismiss"}, requireAll = false) public static void bindingDate(TextView view, String pattern, String errorMessage, boolean autoDismiss) { if (autoDismiss) { EditTextHandler.disableErrorOnChanged(view); } String handledErrorMessage = ErrorMessageHelper.getStringOrDefault(view, errorMessage, R.string.error_message_date_validation); ViewTagHelper.appendValue(R.id.validator_rule, view, new DateRule(view, pattern, handledErrorMessage)); }
@BindingAdapter("content") public static <T> void setContent(RecyclerView recyclerView, List<T> content) { RecyclerView.Adapter adapter = recyclerView.getAdapter(); if (adapter == null) { return; } if (adapter instanceof BookListAdapter) { ((BookListAdapter) adapter).replace((List<Book>) content); } }