简体   繁体   English

如何以编程方式设置下边距?

[英]How to set a bottom margin programmatically?

I have a LinearLayout that already contains multiple of elements. 我有一个已包含多个元素的LinearLayout 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. 然后在下一行中调用它并设置边距,然后将布局参数设置为params,这与边距设置不同。 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. 如果我错了,请原谅我,我只是开始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 :) 如果我错了,有人请告诉我在哪里,因为我有兴趣看到我的错误:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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