Change Linear Layout Top Margin Programmatically Android


Answer :

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

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

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?