如下所示:
RelativeLayout relativeLayout =(RelativeLayout) findViewById(R.id.login); relativeLayout.setPadding(0,40,0,0);其中第一行表示获取到该界面的布局,第二行对该布局使用setPadding()方法,意为规定其内部控件需距该控件的距离。
如下所示:
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指该控件内部内容距离该控件的边距。
