핀수로그
  • [Android] 제약조건 프로그래밍 방식으로 변경하기 | How to move constraint programmatically
    2023년 10월 03일 22시 43분 02초에 업로드 된 글입니다.
    작성자: 핀수
    728x90
    반응형

    제약조건 프로그래밍 방식으로 변경하기

    updateLayoutParams를 이용한다.

    yourView.updateLayoutParams<ConstraintLayout.LayoutParams> {
            topToBottom = targetViewId
            startToEnd = targetViewId 
            bottomToTop = targetViewId
    				// ...
    }

    예시를 위해 텍스트 뷰 하나를 만들고,

    제약조건을 아래와 같이 두었다.

    <TextView
            android:id="@+id/testTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="sorry, can't use this right now"
            app:layout_constraintEnd_toStartOf="@+id/guideline6"
            app:layout_constraintStart_toStartOf="@+id/guideline3"
            app:layout_constraintTop_toBottomOf="parent" />

    현재는 화면 바깥에 존재하도록 되어 있다.

    아무 버튼이나 클릭하면 해당 텍스트 뷰의 제약조건이 변경되도록 해주었다.

    private fun buttonClick() = View.OnClickListener {
        binding.testTextView.updateLayoutParams<ConstraintLayout.LayoutParams> {
            topToBottom = binding.mediumJoinTextLayout.id
        }
    }

    제약조건이 변경되어 원하는 위치로 이동한 것을 확인할 수 있다.


    공부하며 작성된 글이라 잘못된 정보가 있을 수 있습니다.

    말씀해주시면 수정하겠습니다. 감사합니다.

    References

    아래 글을 참고하여 작성 되었습니다.

     

    ConstraintLayout: change constraints programmatically

    I need help with ConstraintSet. My goal is to change view's constraints in code, but I cant figure out how to do this right. I have 4 TextViews and one ImageView. I need to set ImageView constrain...

    stackoverflow.com

     

    728x90
    반응형
    댓글