简体   繁体   English

我可以在运行时以编程方式设置“android:layout_below”吗?

[英]Can I Set "android:layout_below" at Runtime Programmatically?

在运行时创建RelativeLayout时是否可以以编程方式设置android:layout_below的等效项?

Yes:是的:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width.首先,代码通过指定高度和宽度来创建一个新的布局参数。 The addRule method adds the equivalent of the xml properly android:layout_below . addRule方法在android:layout_below正确添加了 xml 的等效android:layout_below Then you just call View#setLayoutParams on the view you want to have those params.然后你只需在你想要拥有这些参数的视图上调用View#setLayoutParams

Alternatively you can use the views current layout parameters and modify them:或者,您可以使用视图当前布局参数并修改它们:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

虽然@jackofallcode 答案是正确的,但它可以写成一行:

((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);

Kotlin version with infix function带中功能的Kotlin版本

infix fun View.below(view: View) {
      (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

Then you can write:然后你可以写:

view1 below view2

Or you can call it as a normal function:或者您可以将其称为普通函数:

view1.below(view2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM