Android中padding与layout_margin的区别与用法
林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka
一、定义
android:layout_margin就是设置view的上下左右边框的额外空间
android:padding是设置内容相对view的边框的距离
padding,含义为“填充”,像垫肩压类似的填充物,一个控件的padding及此控件内部的填充,由此可见padding是以所被定义的控件A为parent控件,而内部的内容物与控件A的间距。而layout_margin是A控件所在的控件为parent控件,是A与其的间距。
其实概念很简单,padding是站在父view的角度描述问题,它规定它里面的内容必须与这个父view边界的距离。margin则是站在自己的角度描述问题,规定自己和其他(上下左右)的view之间的距离,如果同一级只有一个view,那么它的效果基本上就和padding一样了
如
当按钮分别设置以上两个属性时,得到的效果是不一样的。android:paddingLeft="30px"按钮上设置的内容(例如图片)离按钮左边边界30个像素android:layout_marginLeft="30px"整个按钮离左边设置的内容30个像素
二、使用示例
1、两个都不加
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" > <TextView android:layout_width="100dip" android:layout_height="100dip" android:background="#000000" android:text="Hello" /></RelativeLayout>效果:
2、只加padding
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding ="100dip" android:background="#ffffff" > <TextView android:layout_width="100dip" android:layout_height="100dip" android:background="#000000" android:text="Hello" /></RelativeLayout>
效果:
3、只加margin
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" > <TextView android:layout_width="100dip" android:layout_height="100dip" android:background="#000000" android:layout_margin="30dip" android:text="Hello" /></RelativeLayout>效果:
三、注意说明
在LinearLayout、RelativeLayout、TableLayout中,这2个属性都是设置都是有效的
在FrameLayout中,android:layout_margin是无效的,因为FrameLayout里面的元素都是从左上角开始绘制的
在AbsoluteLayout中,没有android:layout_margin属性
在此提醒,xml参数中含有layout的参数项目为定义的控件相对于parent的关联,没有的一般为本身的定义,以上内容与此相符。又类似于gravity跟layout_gravity,带layout的是相对于parent的大体位置,而不带的是自身内部内容的大体位置。
更多相关文章
- android view的xml属性
- 【Android】ListView与Button的共存问题解决
- Android(安卓)绑定数据到界面控件
- textView 属性总结
- ゞAndroid(安卓)- 疑难問題 - 技巧小结 ゞ
- 2020-09-07
- layout中设置图片自适应大小,并且设置最大宽高
- 相对布局
- 【Android开发基础】应用界面主题Theme使用方法