Search code examples
androidlayouttextview

Change the Right Margin of a View Programmatically?


Can this attribute be changed dynamically in Java code?

android:layout_marginRight

I have a TextView, that has to change its position some pixels to the left dynamically.

How to do it programmatically?


Solution

  • EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

    public static void setMargins (View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }
    

    You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

    TextView tv = (TextView)findViewById(R.id.my_text_view);
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
    params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
    tv.setLayoutParams(params);
    

    I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

    NOTE

    Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams