Get constraint's id programmatically

放肆的年华 提交于 2019-12-24 08:30:04

问题


Given the following 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"

I would like to know how to get the id of

app:layout_constraintBottom_toTopOf

(namely "someID") programatically.

Many thanks!


回答1:


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 has the bottomToTop field, which holds the ID of the View for that particular constraint.

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;

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"


来源:https://stackoverflow.com/questions/53343965/get-constraints-id-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!