Change linear layout top margin programmatically android

LayaoutParams usually create confusion while setting margin because of their parent layout... So this MarginLayoutParams is very useful which works with all layouts.

Java Code

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 200; //Ths value 200 is in px... Please convert in DP
params.leftMargin = 100; 
params.topMargin = 200;

Kotlin code

val params: MarginLayoutParams = view!!.layoutParams as MarginLayoutParams
params.width = 200 
params.leftMargin = 100 
params.topMargin = 200

This updates the top margin without the need to update the other margin values.

LinearLayout layout = (LinearLayout) findViewById(R.id.your_linear_layout);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
layoutParams.topMargin = 200;
layout.setLayoutParams(layoutParams);

use this

    layout = (LinearLayout) findViewById(R.id.layuout);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(30, 20, 30, 0);
layout.setLayoutParams(layoutParams );

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