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

xiaoxiao2021-02-28  61

一.问题描述

在设计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指该控件内部内容距离该控件的边距。

转载请注明原文地址: https://www.6miu.com/read-71583.html

最新回复(0)