-2

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?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 3
    https://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically – Xenolion Dec 23 '17 at 10:33
  • 1
    Possible duplicate of [In Android, how do I set margins in dp programmatically?](https://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically) – MechMK1 Dec 23 '17 at 11:28

3 Answers3

1

You can use following code to do so.

 LinearLayoutview ll= findViewById(R.id.linearLayout); //or however you need it
 LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ll.getLayoutParams();

margins are accessible via

lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;

Now you can use the code

 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
 params.setMargins(20,20,20,20);
 ll.setLayoutParams(params);
Manish Singh Rana
  • 822
  • 1
  • 13
  • 26
1

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...

Tarlan Ahad
  • 370
  • 4
  • 15
0

Need use type of: MarginLayoutParams

Try this:

MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
    params.width = 200; params.leftMargin = 100; params.topMargin = 200;

Code Example for MarginLayoutParams:

http://www.codota.com/android/classes/android.view.ViewGroup.MarginLayoutParams

Tara
  • 692
  • 5
  • 23