Android 设置与外部控件距离(setPadding 和setMargin的使用)

一.问题描述

在设计UI过程中,想使图片处于屏幕的特定位置(如下图1),但发现图片总是在顶端(如下图2):
预实现的界面 实际实现的界面
                          图一:欲实现的界面                              图二:实际的界面

二.解决办法

2.1使用setPadding

如下所示:

RelativeLayout relativeLayout =(RelativeLayout) findViewById(R.id.login); 
relativeLayout.setPadding(0,40,0,0);

其中第一行表示获取到该界面的布局,第二行对该布局使用setPadding()方法,意为规定其内部控件需距该控件的距离。

2.2使用setMargin

如下所示:

ImageView applicationImageView = (ImageView) findViewById(R.id.app_imageView);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) applicationImageView.getLayoutParams();
layoutParams.setMargins(0,GetDeviceWideAndHeight.getHeight(this)/10,0,0);
applicationImageView.setLayoutParams(layoutParams);

首先根据图片的id获取到该图片,然后使用getLayoutParams()方法获取到该图片的布局参数(注意这里布局参数可能是RelativeLayout.LayoutParams或LinearLayout.LayoutParams等类型的),进而使用setMargin()方法设置该图片与其父容器的距离。拓展一下:这里使用的setMargin()方法其实是MarginLayoutParams的方法, 因RelativeLayout.LayoutParams是继承MarginLayoutParams的,所以可以用setMargin设置距离。

三.总结

setPadding():以外部控件的角度,规定其内部控件与其的距离
setMargin():以内部控件的角度,规定外部控件与其的距离(注意是用对应的LayoutParams调用该方法)
这与在xml布局文件中使用margin和padding类似:
android:layout_marginLeft指该控件距离边父控件的边距,
android:paddingLeft指该控件内部内容距离该控件的边距。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值