Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a bottom margin programmatically?

I have a LinearLayout that already contains multiple of elements. I want to programmatically add a bottom margin.

I add the following snippets in the adapter code.

Both don't work.

View linearLayout = convertView.findViewById(R.id.spinnerL);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)linearLayout.getLayoutParams();
params.setMargins(0, 0, 0, 10);
linearLayout.setLayoutParams(params);

This one even removes my element:

View linearLayout = convertView.findViewById(R.id.spinnerL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 10);

linearLayout.setLayoutParams(layoutParams);

What am I doing wrong? How can I add the margin at runtime?

like image 363
jikazali Avatar asked Aug 01 '26 02:08

jikazali


1 Answers

In your first method, you basically said:

params is a variable that will call linearLayout.getLayoutParams();

Then in the next line, you called it and set your margins, but then you set your layout parameters to params, which isn't the same thing as your margin settings. Try making something like:

View linearLayout =  convertView.findViewById(R.id.spinnerL);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)linearLayout.getLayoutParams();
        params.setMargins(0, 0, 0, 10);
        linearLayout.setLayoutParams(params);
        linearLayout.requestLayout();

Do excuse me if I'm wrong, I am only beginning Java. But that's what I understood from your first method. If I am wrong, someone please tell me where because I am interested in seeing my mistake :)

like image 182
micoror1 Avatar answered Aug 02 '26 17:08

micoror1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!