以编程方式获取约束的 ID
Get constraint's id programmatically
给出以下 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"
我想知道如何获取
的id
app:layout_constraintBottom_toTopOf
(即 "someID")以编程方式。
非常感谢!
该属性值保存在 ImageView
的 LayoutParams
中,在本例中具体为 ConstraintLayout.LayoutParams
,因为其父项是 ConstraintLayout
。
ConstraintLayout.LayoutParams
具有 bottomToTop
字段,其中包含该特定约束的 View
的 ID。
只需获取 ImageView
的 LayoutParams
,将它们转换为 ConstraintLayout.LayoutParams
,然后从上述字段中获取您的 ID。例如:
ImageView image = findViewById(R.id.someTag);
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) image.getLayoutParams();
int bottomToTopId = lp.bottomToTop;
如果出于某种原因,您需要该 ID 的实际资源名称,您可以照常使用 Resources#getResourceEntryName()
方法获取它。即:
String viewIdName = getResources().getResourceEntryName(bottomToTopId); // returns "someID"
给出以下 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"
我想知道如何获取
的idapp:layout_constraintBottom_toTopOf
(即 "someID")以编程方式。
非常感谢!
该属性值保存在 ImageView
的 LayoutParams
中,在本例中具体为 ConstraintLayout.LayoutParams
,因为其父项是 ConstraintLayout
。
ConstraintLayout.LayoutParams
具有 bottomToTop
字段,其中包含该特定约束的 View
的 ID。
只需获取 ImageView
的 LayoutParams
,将它们转换为 ConstraintLayout.LayoutParams
,然后从上述字段中获取您的 ID。例如:
ImageView image = findViewById(R.id.someTag);
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) image.getLayoutParams();
int bottomToTopId = lp.bottomToTop;
如果出于某种原因,您需要该 ID 的实际资源名称,您可以照常使用 Resources#getResourceEntryName()
方法获取它。即:
String viewIdName = getResources().getResourceEntryName(bottomToTopId); // returns "someID"