Set Margins in a Linearlayout Programmatically

Set margins in a LinearLayout programmatically

Here is a little code to accomplish it:

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);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);

How to add Margin/padding in LinearLayout programmatically?

Try this one code

    private void createRow() { //got

horizontalLayout = new LinearLayout(this);

LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalParams.setMargins(15, 5, 15, 5); // LEFT, TOP, RIGHT, BOTTOM
horizontalLayout.setLayoutParams(horizontalParams);
horizontalLayout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark));

createSpinner();
createCheckbox();
createEditText();

verticallayout.addView(horizontalLayout, horizontalParams);
}

hope so it will be useful for you. :)

In Android, how do I set margins in dp programmatically?

You should use LayoutParams to set your button margins:

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

Depending on what layout you're using you should use RelativeLayout.LayoutParams or LinearLayout.LayoutParams.

And to convert your dp measure to pixel, try this:

Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);

Margins of a LinearLayout, programmatically with dp

You can use DisplayMetrics and determine the screen density. Something like this:

int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels

As I remember it's better to use flooring for offsets and rounding for widths.

Change linear layout top margin programmatically android


   layout = (LinearLayout) findViewById(R.id.layoutbtnlinear_aboutme);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout.getLayoutParams();
params.setMargins(0, 50, 0, 0);
layout.setLayoutParams(params);

Set margin of a LinearLayout inside a RealtiveLayout programmatically- not working

The way it works is Layout params that one should be using should be from its parent ...

In your case LinearLayout was inside RelativeLayout so, one should be using RelativeLayout.LayoutParams for the purpose



Related Topics



Leave a reply



Submit