I'm trying to make a very basic card game. I want to create a bunch of TextView
s dynamicly in MainActivity.kt
to be stacked on the exact position of another TextView as a placeholder, that was created in the activity_main.xml
I need to be able to move these objects to different positions by changing the position constraints.
I searched the docs but could not find how to set the constraints programatically during runtime. Setting x and y does not work because I'm using constraints.
How to set tv's constraint to be placeholder's top and margin? Something like:
tv.layoutParams.topToTopOf = "@id/deck_placeholder"
tv.layoutParams.marginLeft = "10dp"
to achieve what the xml sets below
app:layout_constraintEnd_toEndOf="@id/deck_placeholder"
app:layout_constraintTop_toTopOf="@id/deck_placeholder"
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/deck_placeholder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="DD"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var layout = findViewById<ConstraintLayout>(R.id.main_layout)
val placeholder = findViewById<TextView>(R.id.deck_placeholder)
for (i in 1..52) {
var tv = TextView(this)
tv.text = i.toString()
tv.id = generateViewId()
//TODO: how to set constraint and position here
//tv.layoutParams = placeholder.layoutParams
layout.addView(tv)
}
}
}
The results are as shown here. The generated TextViews should be on the right side of the screen where DD is.
I tried to copy the layout parameters of the placeholder and the cards are on the right place, but how can I move it to another place later by specifying the constraints and margins?
Or is there a better Layout to use so I can put X and Y coordinates but is still responsive to different screen sizes/orientation?
Using Android Studio 4.1.3 with Kotlin. Thank you for any help.