以编程方式获取约束的ID

以编程方式获取约束的ID

问题描述:

给出以下xml:

<ImageView
    android:id="@+id/someTag"
    android:layout_width="10dp"
    android:layout_height="10dp"
    android:layout_marginBottom="12dp"
    android:layout_marginStart="8dp"
    android:tag="someTag"
    app:layout_constraintBottom_toTopOf="@+id/someID"
    app:layout_constraintStart_toEndOf="@+id/someID"

我想知道如何获取

app:layout_constraintBottom_toTopOf

(即 someID

非常感谢!

该属性值被保存在 ImageView LayoutParams 中,具体来说是 ConstraintLayout.LayoutParams ,在在这种情况下,因为它的父级是 ConstraintLayout

That attribute value is held in the ImageView's LayoutParams, which are specifically ConstraintLayout.LayoutParams, in this case, since its parent is the ConstraintLayout.

ConstraintLayout.LayoutParams 具有 bottomToTop 字段,其中包含该特定约束的视图的I​​D。

只需获取 ImageView LayoutParams ,并将其转换为 ConstraintLayout.LayoutParams ,然后从上述字段中获取您的ID。例如:

Simply get the ImageView's LayoutParams, cast them to ConstraintLayout.LayoutParams, and get your ID from the aforementioned field. For example:

ImageView image = findViewById(R.id.someTag);
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) image.getLayoutParams();
int bottomToTopId = lp.bottomToTop;






如果出于某种原因,您需要实际ID的资源名称,您可以使用 Resources#getResourceEntryName()方法照常获取它。即:


If, for some reason, you need the actual resource name for that ID, you can get it per usual with the Resources#getResourceEntryName() method. That is:

String viewIdName = getResources().getResourceEntryName(bottomToTopId); // returns "someID"