Method 1: According to the Android developer website, whenever you use ViewStub, its layout settings are passed to the inflated child device. Therefore, to set the layout parameters, such as marginLeft, marginTop, marginRight, marginBottom, you must set the values โโin the ViewStub, which will be transferred to inflated children.

Method 2: otherwise, after the ViewStub becomes visible, you can dynamically create LayoutParams and set it to the ViewGroup. This also works.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.leftMargin =getResources().getDimensionPixelSize(R.dimen.four); params.rightMargin=getResources().getDimensionPixelSize(R.dimen.four); params.bottomMargin=getResources().getDimensionPixelSize(R.dimen.eight); findViewById(R.id.linearLayout).setLayoutParams(params);
source share