Search code examples
javaandroidandroid-linearlayout

get and set layout_margin java


I to want get and set margin of my LinearLayout from java. I do not want set like right,left, top, bottom etc. I just want set simple margin from all side. I know I can do it via XML but I do know how can I do it via java.

I have done via xml is like below

android:layout_margin="20dp"

Anyone can please suggest me how can I do it via java?


Solution

  • To set margin to the view you can use this code:

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    
    layoutParams.setMargins(30, 20, 30, 0);


    To get the margin of view use this code

    View view = findViewById(...) //or however you need it
    LayoutParams lp = (LayoutParams) view.getLayoutParams();
       // margins are accessible via
    
    lp.leftMargin;
    lp.rightMargin;
    lp.topMargin;
    lp.bottomMargin;
    
    // perhaps ViewGroup.MarginLayoutParams will work for you. It's a base class for //other LayoutParams.
    
    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

    Note: Sorry for using snippet... It will work like a charm...