Search code examples
androidtextviewimageviewandroid-relativelayout

Programmatically move a view Android


I have an imageView that I want to move given a specific situation.

Initially I have a Relative layout with two textViews and an imageview. The textViews are oriented with one above the other. The imageView is set

android:layout_below="@id/text_view1"
android:layout_toEndOf="@+id/text_view2".

In the logic text_view2 is removed when a specific condition is met. I want to programmatically move the imageView to the end of text_view1 when this condition is met. Essentially when text_view2 is removed, I want to set the imageView to

android:layout_toEndOf="@+id/text_view1"

I don't believe setting X,Y,Z values is appropriate here because programmatically, I don't know where the imageView will show up given different screen sizes, and densities. I just need it to move to the end of the first textView.


Solution

  • Take a look at RelativeLayout.LayoutParams. You will need to manipulate the layout rules in the layout params as follows:

    // Make textView2 invisible
    tv2.visibility = View.INVISIBLE
    // Get the LayoutParams of the ImageView
    val ivParams = iv.layoutParams as RelativeLayout.LayoutParams
    // Change the rule to be to the right of textView1
    ivParams.addRule(RelativeLayout.RIGHT_OF, tv1.id)
    // Since the placement of textView2 is changing, request a layout.
    iv.requestLayout()
    

    Consider using "END_OF" instead of "RIGHT_OF".