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

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

问题描述

我试图用Java(不是XML 的)来创建与填充屏幕按钮的LinearLayout中,并且有利润。这里是code,它的工作原理没有边距:

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 ,但没有重量构件,它没有好。而且,如果你通过它 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.

这是不可能的?因为它肯定看起来它,它不会是第一款Android布局任务,你只能做的XML。

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

推荐答案

下面是一个小code来完成它:

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天全站免登陆