以编程方式在 LinearLayout 中设置边距 [英] Set margins in a LinearLayout programmatically

查看:38
本文介绍了以编程方式在 LinearLayout 中设置边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java(而不是 XML)创建一个 LinearLayout,其中的按钮可以填充屏幕并具有边距.这是没有边距的代码:

I'm trying to use Java (not XML) to create a LinearLayout with buttons that fill the screen, and have margins. Here is code that works without margins:

LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
for (int r = 0; r < 6; ++r) {
    Button btn = new Button(this);
    btn.setText("A");

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
    lp.weight = 1.0f; // This is critical. Doesn't work without it.
    buttonsView.addView(btn, lp);
}

ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(buttonsView, lp);

所以这很好用,但是你到底如何给按钮留出边距,以便它们之间有空间?我尝试使用 LinearLayout.MarginLayoutParams,但它没有 weight 成员,所以不好.如果你在它的构造函数中传递它 lp ,它也不起作用.

So that works fine, but how on earth do you give the buttons margins so there is space between them? I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good. And it doesn't work if you pass it lp in its constructor either.

这不可能吗?因为它看起来确实如此,而且它不会是您只能在 XML 中执行的第一个 Android 布局任务.

Is this impossible? Because it sure looks it, and it wouldn't be the first Android layout task you can only do in XML.

推荐答案

这里有一小段代码来完成它:

Here is a little code to accomplish it:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(30, 20, 30, 0);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);

这篇关于以编程方式在 LinearLayout 中设置边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆