相当于 android:layout_above="@+id/foo"

Equivalent of android:layout_above="@+id/foo"

在 XML 你可以做:

android:layout_above="@+id/foo" 

使一个元素位于另一个元素之上foo

如何以编程方式执行此操作?

虽然 RelativeLayout.LayoutParams 可以添加规则 RelativeLayout.ABOVE 不允许我指定我希望我的视图位于哪个元素之上。

that does not allow me to specify which element I want my view to be above.

当然可以

[来自文档](http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int, int))

anchor The id of another view to use as an anchor, or a boolean value (represented as TRUE for true or 0 for false). For verbs that don't refer to another sibling (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1.

文档中有两个 addRule() 方法。只需使用带有第二个参数的那个,并给出你希望它锚定在上面的 View 的 id。

事实上,你提到的那个,明确地说

This method should only be used for constraints that don't refer to another sibling

(强调我的)

您必须为视图设置一个 ID。您可以执行 myview.setId(id) 或在资源文件 ids.xml 中声明一个 id,然后 setId(R.id.declared_id).

link: How can I assign an ID to a view programmatically?