[java] Set margins in a LinearLayout programmatically

I'm trying to use Java (not XML) to create a LinearLayout with buttons that fill the screen, and have margins. Here is code that works without margins:

LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
for (int r = 0; r < 6; ++r) {
    Button btn = new Button(this);
    btn.setText("A");

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
    lp.weight = 1.0f; // This is critical. Doesn't work without it.
    buttonsView.addView(btn, lp);
}

ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(buttonsView, lp);

So that works fine, but how on earth do you give the buttons margins so there is space between them? I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good. And it doesn't work if you pass it lp in its constructor either.

Is this impossible? Because it sure looks it, and it wouldn't be the first Android layout task you can only do in XML.

This question is related to java android layout view margin

The answer is


Here a single line Solution:

((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)


Try this

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);

I have set up margins directly using below code

LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(3, 300, 3, 3); 
layout.setLayoutParams(params);

Only thing here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams, or else there will be an error.


 MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
 layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

Due to variation in device screen pixel densities its good to always use DIP unit to set margin programmatically. Like below_

//get resources
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

//get layout params...
LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.setMargins(Math.round(pxLeftMargin), Math.round(pxTopMargin), Math.round(pxRightMargin), Math.round(pxBottomMargin));

//set margin...
yourLayoutTOsetMargin.setLayoutParams(params); 

Hope this will help.


To add margins directly to items (some items allow direct editing of margins), you can do:

LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
    ((MarginLayoutParams) lp).topMargin = ...;
    ((MarginLayoutParams) lp).leftMargin = ...;
    //... etc
}
else
    Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );

...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.


So that works fine, but how on earth do you give the buttons margins so there is space between them?

You call setMargins() on the LinearLayout.LayoutParams object.

I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.

LinearLayout.LayoutParams is a subclass of LinearLayout.MarginLayoutParams, as indicated in the documentation.

Is this impossible?

No.

it wouldn't be the first Android layout task you can only do in XML

You are welcome to supply proof of this claim.

Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.


Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to layout

This view is not constrained What's the difference between align-content and align-items? CSS Flex Box Layout: full-width row and columns Fill remaining vertical space with CSS using display:flex What is setContentView(R.layout.main)? How to change line color in EditText Scrolling a flexbox with overflowing content UICollectionView - Horizontal scroll, horizontal layout? How to style a div to be a responsive square? 100% width Twitter Bootstrap 3 template

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to margin

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Removing body margin in CSS How do I force a vertical scrollbar to appear? How to adjust gutter in Bootstrap 3 grid system? How to disable margin-collapsing? Why is there an unexplainable gap between these inline-block div elements? Remove "whitespace" between div element Remove all padding and margin table HTML and CSS Using margin / padding to space <span> from the rest of the <p>