声明

本文属于个人所有,转载注明出处:http://blog.csdn.net/hnulwt/article/details/43671687

问题描述

今天在做android的界面,不过需要用java代码来动态生成一个界面,写起来不算难,但是在控制每行与上行的间隔的时候遇到了问题。在layout xml文件中,通过书写android:layout_marginLeft android:layout_marginTop 等等几个方法来控制当前view与旁边view的间隔距离。但是如何在java中书写呢?

解决方案

在java代码中输写,我只发现了有setPadding(left, top, right, bottom),但是并没有setMargin或者setLayoutMargin方法来控制view间隔。
查询了谷歌官网,在官网查到了ViewGroup.MarginLayoutParams类,资料如下:

XML Attributes
Attribute Name Related Method Description
android:layout_marginBottom setMargins(int,int,int,int) Specifies extra space on the bottom side of this view.
android:layout_marginEnd setMarginEnd(int) Specifies extra space on the end side of this view.
android:layout_marginLeft setMargins(int,int,int,int) Specifies extra space on the left side of this view.
android:layout_marginRight setMargins(int,int,int,int) Specifies extra space on the right side of this view.
android:layout_marginStart setMarginStart(int) Specifies extra space on the start side of this view.
android:layout_marginTop setMargins(int,int,int,int) Specifies extra space on the top side of this view.

可以看到他们属性还是有对应的方法的:setMargins 和 setMarginEnd等等方法。
但是这个方法怎么用呢。为此我又进行了一系列探索,发现应该用下面方式使用:

        LinearLayout line = (LinearLayout) findViewById(R.id.layoutbtnlinear_aboutme);        LinearLayout.LayoutParams params = (LayoutParams) line.getLayoutParams();        params.setMargins(0, 1, 0, 0);        line.setLayoutParams(params);

但是这种方式其实还是有点问题的,我的LinearLayout是在java代码中生成的,好吧,继续寻找方法:

LinearLayout ll = new LinearLayout(this);ll.setOrientation(LinearLayout.VERTICAL);LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);layoutParams.setMargins(30, 20, 30, 0);Button okButton=new Button(this);okButton.setText("text");ll.addView(okButton, layoutParams);

更多相关文章

  1. Android获取系统时间方法的总结
  2. Intent传递对象的两种方法(Serializable,Parcelable)
  3. [置顶] Android之ContextMenu的使用方法以及与OptionMenu的区别
  4. INSTALL_FAILED_CONFLICTING_PROVIDER 错误解决方法
  5. File "/Volumes/android/.repo/repo/main.py", line 531, in _Ma
  6. Android Adapter 接口中几个方法的研究
  7. Android 的 dex2jar 和 jd-gui 反编译 apk 源代码

随机推荐

  1. 初学Android时,运行SDK的例子出现警告
  2. Google android初级开发之 : android 编
  3. Activity去除标题栏和状态栏
  4. Android设置Settings实现:PreferenceActiv
  5. Android使用gradle生成maven库,上传githu
  6. Android之开发常用颜色
  7. 像写Flutter一样开发Android原生应用
  8. Android 中文API (67) —— BluetoothClass
  9. 使用ImageView 加上 Edittext做出自定义
  10. android和PC(Python)通过USB(adb模式)基于Soc