android.databinding.BindingAdapter Java Examples

The following examples show how to use android.databinding.BindingAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BindingAdapters.java    From Flubber with Apache License 2.0 6 votes vote down vote up
@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()));
            }));
}
 
Example #2
Source File: DataBindingAdapters.java    From mobikul-standalone-pos with MIT License 6 votes vote down vote up
@BindingAdapter(value = {"imageUrl", "placeholder", "sizeDevider"}, requireAll = false)
    public static void loadImage(ImageView view, String imageUrl, Drawable placeHolder, double sizeDevider) {
        if (imageUrl != null && imageUrl.isEmpty()) {
            imageUrl = null;
        }
        /*LOAD WITHOUT PLACE HOLDER*/
        if (imageUrl != null && !imageUrl.equalsIgnoreCase("")) {
            try {
                Glide.with(view.getContext())
                        .load(imageUrl)
//                    .error(R.drawable.ic_error)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .dontAnimate()
                        .into(view);
            } catch (Exception e) {
                view.setImageResource(R.drawable.ic_error);
            }
        } else {
            view.setImageResource(R.drawable.ic_product_placeholder);
            Log.d("Placeholder Image", imageUrl + "---" + view);
        }
    }
 
Example #3
Source File: ViewGroupAdapter.java    From MVVM-JueJin with MIT License 6 votes vote down vote up
/**
 * (伪)双向 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);
        }
    }
}
 
Example #4
Source File: ViewPagerAdapter.java    From MVVM-JueJin with MIT License 6 votes vote down vote up
/**
 * (伪)双向 databinding: 同 {@link RecyclerViewAdapter#setDataTwoWay(RecyclerView, ListVM, List)}
 *
 * @param container
 * @param vm
 * @param datas
 * @param <T>
 */
@BindingAdapter({"vm", "data"})
public static <T> void setDataTwoWay(final ViewPager 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);
        }
    }
}
 
Example #5
Source File: FlexboxBindingAdapter.java    From WanAndroid with GNU General Public License v3.0 6 votes vote down vote up
@BindingAdapter(value = {"fullFlexData", "postTreeViewModel"})
public static void fullFlexData(FlexboxLayout layout, TreeBean treeBean, PostTreeViewModel viewModel) {
    layout.removeAllViews();
    if (treeBean.getChildren() == null || treeBean.getChildren().size() == 0) return;
    Context context = layout.getContext();
    for (TreeBean tree : treeBean.getChildren()) {
        TextView textView = new TextView(context);
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewHelper.dpToPx(context, 40)));
        textView.setTextColor(ContextCompat.getColor(context, R.color.textSecondary));
        textView.setBackgroundResource(R.drawable.btn_rounded_outline);
        textView.setGravity(Gravity.CENTER);
        textView.setFocusable(true);
        textView.setClickable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            textView.setForeground(ContextCompat.getDrawable(context, R.drawable.ripple_theme_small));
        }
        textView.setText(tree.getName());
        textView.setOnClickListener(v -> viewModel.mTagClickEvent.setValue(treeBean.setCheckedChild(tree)));
        layout.addView(textView);
    }
}
 
Example #6
Source File: LineChartExtensions.java    From exchange-rates-mvvm with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: BindingAdapters.java    From EasyNLU with Apache License 2.0 6 votes vote down vote up
@BindingAdapter("textRepeat")
public static void textRepeat(TextView view, long repeatDuration){
    if(repeatDuration != -1){
        final long[] duration = {0};
        final String[] unit = {""};

        zip(KEYS_MUL, KEYS_TIME)
            .forEach((mul, time) ->{
                if(repeatDuration % mul == 0){
                    duration[0] = repeatDuration / mul;
                    unit[0] = time;
                    return false;
                }

                return true;
            });

        if(duration[0] > 0){
            if(duration[0] == 1)
                view.setText(String.format("Every %s", unit[0]));
            else
                view.setText(String.format("Every %d %ss", (int)duration[0], unit[0]));
        }
    }
}
 
Example #8
Source File: MessageBindingAdapter.java    From Android-App-Architecture-MVVM-Databinding with Apache License 2.0 5 votes vote down vote up
/**
 * Binding "messageSource" to display a message. Here Toast is used but more complex strategy may be applied.
 *
 * @param view the View which binds the message source.
 * @param oldMessageSource the last message source.
 * @param messageSource the message source.
 */
@BindingAdapter({"messageSource"})
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public static void showMessage(@NonNull final View view, @Nullable final IMessageSource oldMessageSource,
        @Nullable final IMessageSource messageSource) {
    if (view == null || messageSource == null || oldMessageSource == messageSource) {
        return;
    }

    final int duration = messageSource.getType() == Type.ERROR ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
    Toast.makeText(view.getContext(), messageSource.getMessageId(), duration).show();
}
 
Example #9
Source File: HuePickerBindingAdapters.java    From spline with Apache License 2.0 5 votes vote down vote up
/**
 * This is how you implement 2-way data binding of a custom attribute if you want to maintain
 * a custom listener interface - OnHueChangeListener, in this case - while also leveraging
 * the synthetic attributes hueAttrChanged (the InverseBindingListener). For an example of
 * how to implement custom 2-way binding with just the synthetic AttrChanged attribute's
 * InverseBindingListener, see DocumentView or LayerListView's currentLayer 2-way binding
 * (along with the InverseBindingMethod declarations in DocumentViewModelBindingAdapters).
 *
 * @param view                   The view we're 2-way binding to.
 * @param onHueChangeListener    The OnHueChangeListener bound by the developer on the view
 *                               in question.
 * @param inverseBindingListener Synthetic attribute representing an InverseBindingListener
 *                               for changes to the hue attribute.
 */
@BindingAdapter(value = {"onHueChange", "hueAttrChanged"}, requireAll = false)
public static void setListeners(HuePicker view,
                                final HuePicker.OnHueChangeListener onHueChangeListener,
                                final InverseBindingListener inverseBindingListener) {
    HuePicker.OnHueChangeListener newListener;
    if (inverseBindingListener == null) {
        // If the synthetic listener param is null, just keep track of the listener set in
        // the binding
        newListener = onHueChangeListener;
    } else {
        // Otherwise define a new listener to wraps both listeners and invoke them at the
        // right time within the new listener if they are non-null
        newListener = new HuePicker.OnHueChangeListener() {
            @Override
            public void onHueChange(HuePicker huePicker, float hue) {
                if (onHueChangeListener != null) {
                    onHueChangeListener.onHueChange(huePicker, hue);
                }
                inverseBindingListener.onChange();
            }
        };
    }

    // Use track listener to record listener we're adding and return any old listeners
    // registered through this method so that on rebind we don't add duplicate listeners
    HuePicker.OnHueChangeListener oldListener = ListenerUtil.trackListener(view, newListener,
            R.id.hueChangeListener);

    // Remove the old listener we set using this BindingAdapter, if there is one
    if (oldListener != null) {
        view.removeHueChangeListener(oldListener);
    }

    // Add our new listener
    if (newListener != null) {
        view.addHueChangeListener(newListener);
    }
}
 
Example #10
Source File: Tool.java    From Sunshine with Apache License 2.0 5 votes vote down vote up
@BindingAdapter({"iconRes"})
    public static void loadImage(ImageView iconView, int iconRes) {
//        Picasso.with(iconView.getContext())
//                .load(iconRes)
//                .into(iconView);
        //用Picasso真是大材小用了
        iconView.setImageResource(iconRes);
    }
 
Example #11
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * EditText重新获取焦点的事件绑定
 */
@BindingAdapter(value = {"requestFocus"}, requireAll = false)
public static void requestFocusCommand(EditText editText, final Boolean needRequestFocus) {
    if (needRequestFocus) {
        editText.setSelection(editText.getText().length());
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
    editText.setFocusableInTouchMode(needRequestFocus);
}
 
Example #12
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@BindingAdapter(value = {"onCheckedChangedCommand"}, requireAll = false)
public static void onCheckedChangedCommand(final RadioGroup radioGroup, final BindingCommand<String> bindingCommand) {
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            bindingCommand.execute(radioButton.getText().toString());
        }
    });
}
 
Example #13
Source File: DataBindUtil.java    From MultiItem with Apache License 2.0 5 votes vote down vote up
/**
 * 通过android:imageUrl可以在xml布局中直接为ImageView设置url地址,这样方便业务中使用第三方库加载网络图片
 *
 * @param imageView xml中ImageView实例
 * @param imgUrl    网络图片地址
 */
@BindingAdapter({"android:imageUrl"})
public static void setImageViewResource(ImageView imageView, String imgUrl) {
    Context context = imageView.getContext();
    //此处通过imgUrl字符串获取资源ID,具体使用根据业务需要
    int resId = context.getResources().getIdentifier(imgUrl, "drawable", context.getPackageName());
    imageView.setImageResource(resId);
}
 
Example #14
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@BindingAdapter({"itemView", "observableList"})
public static void addViews(ViewGroup viewGroup, final ItemBinding itemBinding, final ObservableList<IBindingItemViewModel> viewModelList) {
    if (viewModelList != null && !viewModelList.isEmpty()) {
        viewGroup.removeAllViews();
        for (IBindingItemViewModel viewModel : viewModelList) {
            ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(Utils.getContext()),
                    itemBinding.layoutRes(), viewGroup, true);
            binding.setVariable(itemBinding.variableId(), viewModel);
            viewModel.injecDataBinding(binding);
        }
    }
}
 
Example #15
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param bindingCommand //绑定监听
 */
@SuppressWarnings("unchecked")
@BindingAdapter(value = {"onCheckedChangedCommand"}, requireAll = false)
public static void setCheckedChanged(final CheckBox checkBox, final BindingCommand<Boolean> bindingCommand) {
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            bindingCommand.execute(b);
        }
    });
}
 
Example #16
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 回调控件本身
 *
 * @param currentView
 * @param bindingCommand
 */
@BindingAdapter(value = {"currentView"}, requireAll = false)
public static void replyCurrentView(View currentView, BindingCommand bindingCommand) {
    if (bindingCommand != null) {
        bindingCommand.execute(currentView);
    }
}
 
Example #17
Source File: ViewAdapter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * view的onLongClick事件绑定
 */
@BindingAdapter(value = {"onLongClickCommand"}, requireAll = false)
public static void onLongClickCommand(View view, final BindingCommand clickCommand) {
    RxView.longClicks(view)
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object object) throws Exception {
                    if (clickCommand != null) {
                        clickCommand.execute();
                    }
                }
            });
}
 
Example #18
Source File: BindingUtils.java    From NewsApp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Utility method for Image url If image url is valid then it is parsed else
 * Article url provides url to website and icon finder utility is used to find icon
 *
 * @param imageView  Default view passed for displaying image
 * @param url        Url of the image
 * @param articleUrl URL to the article
 */
@BindingAdapter({"bind:url", "bind:articleUrl"})
public static void loadThumbnailImage(ImageView imageView, String url, String articleUrl) {
    Context context = imageView.getContext();
    if (url == null) {
        String iconUrl = "https://besticon-demo.herokuapp.com/icon?url=%s&size=80..120..200";
        url = String.format(iconUrl, Uri.parse(articleUrl).getAuthority());
    }
    GlideApp.with(imageView)
            .load(url)
            .apply(NewsGlideModule.roundedCornerImage(new RequestOptions(), imageView.getContext(), 4))
            .placeholder(context.getResources().getDrawable(R.color.cardBackground))
            .into(imageView);
}
 
Example #19
Source File: EditBindingAdapter.java    From Fairy with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #20
Source File: RecyclerViewBindings.java    From okuki with Apache License 2.0 5 votes vote down vote up
@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);

}
 
Example #21
Source File: DataBindingAdapter.java    From Android-App-Architecture-MVVM-Databinding with Apache License 2.0 5 votes vote down vote up
/**
 * Binding "visibility" to the a boolean value.
 *
 * @param view the View to set visibility
 * @param value the boolean value to bind. True for VISIBLE and False for GONE.
 */
@BindingAdapter({"visibility"})
public static void setVisibilityByBoolean(final View view, final boolean value) {
    if (value) {
        view.setVisibility(View.VISIBLE);
    } else {
        view.setVisibility(View.GONE);
    }
}
 
Example #22
Source File: BindingUtils.java    From NewsApp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Utility method for Image url If image url is valid then it is parsed else
 * Article url provides url to website and icon finder utility is used to find icon
 * This puts a radius 0 to image
 *
 * @param imageView  Default view passed for displaying image
 * @param url        Url of the image
 * @param articleUrl URL to the article
 */
@BindingAdapter({"bind:urlToImage", "bind:articleUrl"})
public static void loadImage(ImageView imageView, String url, String articleUrl) {
    Context context = imageView.getContext();
    if (url == null) {
        String iconUrl = "https://besticon-demo.herokuapp.com/icon?url=%s&size=80..120..200";
        url = String.format(iconUrl, Uri.parse(articleUrl).getAuthority());
    }
    GlideApp.with(imageView)
            .load(url)
            .apply(NewsGlideModule.roundedCornerImage(new RequestOptions(), imageView.getContext(), 0))
            .placeholder(context.getResources().getDrawable(R.color.cardBackground))
            .into(imageView);
}
 
Example #23
Source File: TextViewAdapter.java    From demo4Fish with MIT License 5 votes vote down vote up
@BindingAdapter(value = {"android:drawableLeft"})
public static void setDrawableLeft(TextView textView, int resID) {
    Drawable leftDrawable = textView.getContext().getResources().getDrawable(resID);
    leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
    textView.setCompoundDrawables(
            leftDrawable,
            null,
            null,
            null);
}
 
Example #24
Source File: RecyclerViewAdapter.java    From MVVM-JueJin with MIT License 5 votes vote down vote up
/**
 * (伪)双向 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);
                        }
                    }
                });
            }
        }
    }
}
 
Example #25
Source File: ImageBindingAdapter.java    From WanAndroid with GNU General Public License v3.0 5 votes vote down vote up
@BindingAdapter("itemUrl")
public static void setImage(ImageView imageView, String url) {
    if (TextUtils.isEmpty(url)) {
        imageView.setVisibility(View.GONE);
        return;
    } else {
        imageView.setVisibility(View.VISIBLE);
    }

    Glide.with(imageView)
            .applyDefaultRequestOptions(PicConfig.itemOptions)
            .load(url)
            .into(imageView);
}
 
Example #26
Source File: MoviesListBinding.java    From android-mvvm-sample with MIT License 5 votes vote down vote up
@BindingAdapter("bind:movies")
public static void setMovies(RecyclerView recyclerView, List<Movie> movies) {
    RecyclerView.Adapter adapter = recyclerView.getAdapter();

    if (adapter != null && adapter instanceof MovieAdapter) {
        ((MovieAdapter) adapter).setMovies(movies);
    } else {
        throw new IllegalStateException("RecyclerView either has no adapter set or the "
                + "adapter isn't of type MovieAdapter");
    }
}
 
Example #27
Source File: ImageBindingAdapter.java    From WanAndroid with GNU General Public License v3.0 5 votes vote down vote up
@BindingAdapter("itemHeadUrl")
public static void setImage3(ImageView imageView, String url) {
    Glide.with(imageView.getContext())
            .applyDefaultRequestOptions(PicConfig.headOptions)
            .load(url)
            .into(imageView);

}
 
Example #28
Source File: ImageBindingAdapter.java    From WanAndroid with GNU General Public License v3.0 5 votes vote down vote up
@BindingAdapter("blurImage")
public static void setBlurImage(ImageView imageView, String url) {
    Glide.with(imageView.getContext())
            .applyDefaultRequestOptions(PicConfig.itemOptions)
            .asBitmap()
            .load(url)
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    Blurry.with(imageView.getContext()).from(resource).into(imageView);
                }
            });

}
 
Example #29
Source File: OrderDialogFragment.java    From From-design-to-Android-part1 with Apache License 2.0 5 votes vote down vote up
@BindingAdapter("app:spanOffset")
public static void setItemSpan(View v, int spanOffset) {
    final String itemText = ((TextView) v).getText().toString();
    final SpannableString sString = new SpannableString(itemText);

    sString.setSpan(new RelativeSizeSpan(1.65f), itemText.length() - spanOffset, itemText.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    ((TextView) v).setText(sString);
}
 
Example #30
Source File: SettingsDialogFragment.java    From nano-wallet-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@BindingAdapter("android:layout_marginTop")
public static void setTopMargin(View view, float topMargin) {
    ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin, Math.round(topMargin),
            layoutParams.rightMargin, layoutParams.bottomMargin);
    view.setLayoutParams(layoutParams);
}