我们平常可以直接在xml里设置margin,如:

<ImageView android:layout_margin="5dip" android:src="@drawable/image" />

但是有些情况下,需要在java代码里来写,可是View本身没有setMargin方法,怎么办呢?

通过查阅android api,我们发现android.view.ViewGroup.MarginLayoutParams有个方法setMargins(left, top, right, bottom).

其直接的子类有: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

使用方法:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 20, 30, 40);
imageView.setLayoutParams(lp);

url:http://greatverve.cnblogs.com/archive/2012/01/29/android-margin.html

MainActivity如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package cn.testfixmargin;
  
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Activity;
/**
 * Demo描述:
 * 在代码中设置布局的属性
 * 比如Margin和居中
 *
 * 注意事项:
 * 参见代码中的详细注释
 */
public class MainActivity extends Activity {
    private TextView mTextView;
    private Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }
    private void init(){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        float density=displayMetrics.density;
        float fontScale = displayMetrics.scaledDensity;
        System.out.println("density="+density+",fontScale="+fontScale);
          
        mTextView=(TextView) findViewById(R.id.textView);
        mButton=(Button) findViewById(R.id.button);
        mButton.setOnClickListener(new OnClickListenerImpl());
          
          
    }
  
    private class OnClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {
//         //--------以下为测试1 在代码中为控件设置Margin-------- 
//         //注意: 
//         //1  此处的new RelativeLayout.LayoutParams(int w, int h)参数w,h指的是 
//         //  该控件的父控件的在布局文件中所设置的宽和高 
//         //2  此处必须使用RelativeLayout.LayoutParams.FILL_PARENT() 
//         //  因为其父类为RelativeLayout所以是其父类的布局参数即RelativeLayout.LayoutParams.XXX 
//         //  注意其官方文档的描述: 
//         //  Set the layout parameters associated with this view.  
//         //  These supply parameters to the parent of this view specifying how it should be arranged. 
//         //  也就是说这个setLayoutParams()是给其父控件看的 
//         //  其实这也好理解:只有父类可以改变子View的位置布局.而不是说子View可以随意 
//         //  按照自己的想法摆放自己的位置,而不受父控件控制 
//           RelativeLayout.LayoutParams layoutParams 
//           =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); 
//           layoutParams.setMargins(280, 0, 0, 0); 
//           mTextView.setLayoutParams(layoutParams); 
//           //--------以上为测试1-------- 
             
             
              
            //--------以下为测试2 在代码中设置控件居中-------- 
            //注意: 
            //1  此处的new RelativeLayout.LayoutParams(int w, int h)参数w,h指的是 
            //  该控件在布局文件中所设置的宽和高 
            //2  同测试1中的描述 
            RelativeLayout.LayoutParams layoutParams=
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            mTextView.setLayoutParams(layoutParams);
            //--------以下为测试2-------- 
              
        }
  
    }
}
 
package cn.testfixmargin;
 
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Activity;
/**
 * Demo描述:
 * 在代码中设置布局的属性
 * 比如Margin和居中
 *
 * 注意事项:
 * 参见代码中的详细注释
 */
public class MainActivity extends Activity {
    private TextView mTextView;
    private Button mButton;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  init();
 }
    private void init(){
  DisplayMetrics displayMetrics = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
     float density=displayMetrics.density;
     float fontScale = displayMetrics.scaledDensity;
     System.out.println("density="+density+",fontScale="+fontScale);
        
     mTextView=(TextView) findViewById(R.id.textView);
     mButton=(Button) findViewById(R.id.button);
     mButton.setOnClickListener(new OnClickListenerImpl());
      
      
    }
 
 private class OnClickListenerImpl implements OnClickListener {
  @Override
  public void onClick(View v) {
//     //--------以下为测试1 在代码中为控件设置Margin--------
//     //注意:
//     //1  此处的new RelativeLayout.LayoutParams(int w, int h)参数w,h指的是
//     //  该控件的父控件的在布局文件中所设置的宽和高
//     //2  此处必须使用RelativeLayout.LayoutParams.FILL_PARENT()
//     //  因为其父类为RelativeLayout所以是其父类的布局参数即RelativeLayout.LayoutParams.XXX
//     //  注意其官方文档的描述:
//     //  Set the layout parameters associated with this view.
//     //  These supply parameters to the parent of this view specifying how it should be arranged.
//     //  也就是说这个setLayoutParams()是给其父控件看的
//     //  其实这也好理解:只有父类可以改变子View的位置布局.而不是说子View可以随意
//     //  按照自己的想法摆放自己的位置,而不受父控件控制
//           RelativeLayout.LayoutParams layoutParams
//           =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
//           layoutParams.setMargins(280, 0, 0, 0);
//           mTextView.setLayoutParams(layoutParams);
//           //--------以上为测试1--------
           
           
    
            //--------以下为测试2 在代码中设置控件居中--------
   //注意:
   //1  此处的new RelativeLayout.LayoutParams(int w, int h)参数w,h指的是
   //  该控件在布局文件中所设置的宽和高
   //2  同测试1中的描述
   RelativeLayout.LayoutParams layoutParams=
      new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
   layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
   mTextView.setLayoutParams(layoutParams);
            //--------以下为测试2--------
    
  }
 
 }
}

main.xml如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >
  
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:layout_marginLeft="20dip"
    />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        android:textSize="25sp"
        android:layout_centerInParent="true"
     />
  
</RelativeLayout>
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     >
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:layout_marginLeft="20dip"
    />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        android:textSize="25sp"
        android:layout_centerInParent="true"
     />
 
</RelativeLayout>

Android利用setLayoutParams在代码中调整布局(Margin和居中)的更多相关文章

  1. android代码中自定义布局

    转载地址:http://blog.csdn.net/luckyjda/article/details/8760214RelativeLayout rl = new RelativeLayout(thi ...

  2. Android在代码中使用布局文件中的一个组件

    使用前必须要把组件与其父组件的关系断开,比如有一个组件的名称为scrollChildLayout,则可以使用下面的代码进行分离 ((ViewGroup)scrollChildLayout.getPar ...

  3. 转--Android如何在java代码中设置margin

    ========  3 在Java代码里设置button的margin(外边距)? 1.获取按钮的LayoutParams LinearLayout.LayoutParams layoutParams ...

  4. Android如何在java代码中设置margin

    习惯了直接在xml里设置margin(距离上下左右都是10dip),如: <ImageView android:layout_margin="10dip" android:s ...

  5. Android 如何在Java代码中手动设置控件的marginleft

    1.定义LayoutParams LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.La ...

  6. android利用反射通过代码收缩通知栏

    最近有个需求,点击通知栏RemoteView中的按钮后要收起通知栏,系统默认是不自动收起的,不过没有找到公开的API可以控制通知栏. 在android.app.StatusBarManager里提供了 ...

  7. android 可以在程序代码中设置样式:style

    <style name="text_style"> <item name="android:textStyle">bold</it ...

  8. 利用 ReSharper 自定义代码中的错误模式,在代码审查之前就发现并修改错误

    多人协作开发的项目总会遇到代码编写风格上的差异.一般工具都能帮我们将常见的差异统一起来——例如 if 的换行:但也有一些不那么通用,但项目中却经常会出现的写法也需要统一. 例如将单元测试中的 Asse ...

  9. Android TextView drawableLeft 在代码中实现

    方法1 Drawable drawable= getResources().getDrawable(R.drawable.drawable); /// 这一步必须要做,否则不会显示. drawable ...

随机推荐

  1. CSS 命名规则

    CSS书写顺序: 位置属性(position, top, right, z-index,display, float等) 大小(width, height, padding, margin) 文字系列 ...

  2. (转)用eclipse创建一个j2ee的web工程后,左面projects窗口中的项目如何没有显示webRoot文件夹,除了src的文件夹,其他都不显示

    左边目录窗口的右上方,有个向下的箭头,点里面的filters,把所有的勾都去掉看看

  3. (转)jquery.validate.js 的 remote 后台验证

    之前已经有一篇关于jquery.validate.js验证的文章,还不太理解的可以先看看:jQuery Validate 表单验证(这篇文章只是介绍了一下如何实现前台验证,并没有涉及后台验证remot ...

  4. CentOS重启与关机

    Linux centos关机与重启命令详解与实战 Linux centos重启命令: 1.reboot 2.shutdown -r now 立刻重启(root用户使用) 3.shutdown -r 1 ...

  5. osg for android (一) 简单几何物体的加载与显示

    1. 首先需要一个OSG for android的环境. (1).NDK 现在Eclipse 对NDK已经相当友好了,已经不需要另外cygwin的参与,具体可以参考 Android NDK开发篇(一) ...

  6. Phpcms V9全站伪静态设置方法

    为什么要伪静态?具体在这里就不说了,你懂的!一方面更新修改后不需要生成静态文件,另一方面为了SEO! 访问规则如下 1 2 list-{$catid}-{$page}.html content-{$c ...

  7. 关于 Delphi 中的Sender和易混淆的概念(转)

    /////////////////////////////////////////////////////// Delphi 中Sender对象的定义///////////////////////// ...

  8. php加密解密实用类

    一个加解密类.如果你想在用户忘记密码时为他或她找回原来的密码,那么这个类是个好用的工具 用户注册的密码一般不会明文保存,总得加个密先.最简单的当然是在数据库sql语句中调用md5函数加密用户密码.这里 ...

  9. 如何使用sublime编辑器运行python程序

    现在越发喜欢sublime编辑器了,不仅界面友好美观.文艺,可扩展性还特别强. sublime本身是不具备运行python程序的能力的,需要做些设置才可以.以下是安装好sublime后设置的步骤: 点 ...

  10. 文件操作类CFile

    CFile file; CString str1= L"写入文件成功!"; wchar_t *str2; if (!file.Open(L"Hello.txt" ...