简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM