Skip to content

Instantly share code, notes, and snippets.

@openback
Created October 8, 2012 05:24
Show Gist options
  • Save openback/3850853 to your computer and use it in GitHub Desktop.
Save openback/3850853 to your computer and use it in GitHub Desktop.
[android] Animate margins with ObjectAnimator
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
/**
* Allows an ObjectAnimator to set/get margins of a view
*/
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();
}
}
@HugoGresse
Copy link

How do you use it ?

@anas-incedo
Copy link

@HugoGresse:
MarginProxy marginProxy = new MarginProxy(<object of the view whose margins you want to animate>);
marginProxy.setBottomMargin(100);

Hope that helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment