Search code examples
androidobjectanimator

How to make android object animator responsive?


Here the value 200 is resulting different on different screens. Is there any way we can solve this problem?

 MarginProxy marginProxy = new MarginProxy(fab);
                        ObjectAnimator marginAnimation = ObjectAnimator.ofInt(marginProxy, "bottomMargin", 530, 200).setDuration(300);
                        marginAnimation.start();

When the animation is on run, the button moves differently on the other screen (pixel) and to the other position on the other device (Samsung J7)
This is the margin proxy class

class MarginProxy {
    private View mView;

    public MarginProxy(View view) {
        mView = view;
    }
public int getLeftMargin() {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    return lp.leftMargin;
}

public void setLeftMargin(int margin) {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    lp.setMargins(margin, lp.topMargin, lp.rightMargin, lp.bottomMargin);
    mView.requestLayout();
}

public int getTopMargin() {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    return lp.topMargin;
}

public void setTopMargin(int margin) {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    lp.setMargins(lp.leftMargin, margin, lp.rightMargin, lp.bottomMargin);
    mView.requestLayout();
}

public int getRightMargin() {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    return lp.rightMargin;
}

public void setRightMargin(int margin) {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    lp.setMargins(lp.leftMargin, lp.topMargin, margin, lp.bottomMargin);
    mView.requestLayout();
}

public int getBottomMargin() {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    return lp.bottomMargin;
}

public void setBottomMargin(int margin) {
    MarginLayoutParams lp = (MarginLayoutParams) mView.getLayoutParams();
    lp.setMargins(lp.leftMargin, lp.topMargin, lp.rightMargin, margin);
    mView.requestLayout();
}
}

Solution

  • Instead of using pixels you have to use Dips.

    public int convertDiptoPix(int dip){
    float scale = getDensity();
    return (int) (dip * scale + 0.5f);}
    

    Then exchange your "200" pixel values to the result of this method.