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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3277196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:26:06  来源:igfitidea点击:

Can I Set "android:layout_below" at Runtime Programmatically?

androidandroid-layoutandroid-relativelayout

提问by AlanH

Is it possible when creating a RelativeLayoutat runtime to set the equivalent of android:layout_belowprogrammatically?

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

回答by Rich Schuler

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 addRulemethod adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParamson the view you want to have those params.

首先,代码通过指定高度和宽度来创建一个新的布局参数。该addRule方法正确添加了 xml 的等效项android:layout_below。然后你只需调用View#setLayoutParams你想要拥有这些参数的视图。

回答by Hymanofallcode

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);

回答by CoolMind

While @Hymanofallcode answer is correct, it can be written in one line:

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

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

回答by Mahmoud

Kotlinversion with infixfunction

带中功能的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)