Home > other >  Changing Views' position in android
Changing Views' position in android

Time:01-11

I'm trying to build a simple app where there's a button and each time it gets clicked, it changes its location on the screen. I don't have any experience at all developing for android so I don't know how to change the view's properties etc.

CodePudding user response:

Try this and enjoy :)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@ id/my_relativeLayout"  // add id to RelativeLayout
    tools:context=".MainActivity">


    <Button
        android:id="@ id/my_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click !" />


</RelativeLayout>

MainActivity.kt

     binding.myBtn.setOnClickListener {
        
      val random = Random
      val relativeLayout = findViewById<RelativeLayout>(R.id.my_relativeLayout)
            
         binding.show.x = random.nextInt(relativeLayout.width - binding.show.width).toFloat()
         binding.show.y = random.nextInt(relativeLayout.height - binding.show.height).toFloat()
        
 }
  •  Tags:  
  • Related