We are creating a View programmatically in onCreate method and trying to set either of the following to that view-
- The topandleftor
- The bottomandright.
But it's not working. These absolute positions can be relative to the screen or to the parent layout. Here is an example to reproduce the same thing-
main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/root"
    android:layout_height="match_parent">
</RelativeLayout>
And here is the MainActivity, where I am trying view programmatically.
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
        val root = findViewById<RelativeLayout>(R.id.root)
        val layoutParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )
        val view = TextView(this)
        view.layoutParams = layoutParams
        view.text = "Test View"
        
        //Applying top and left value in pixels.
        view.top = 100
        view.left = 100
        root.addView(view)
    }
}
top and left values are not getting assign to the view.
We have tried with many other layouts-
- FrameLayout
- LinearLayout
- AbsoluteLayout(deprecated so not considering)
We have also tried to use View#layout() method but it didn't work either.
We have referred to the following articles-
- How can I dynamically set the position of view in Android?
- Usage of forceLayout(), requestLayout() and invalidate()
- Android set view position - setY vs setTop
- https://www.tutorialspoint.com/how-to-set-the-absolute-position-of-a-view-in-android
- https://mindmajix.com/android/absolute-layout
- https://developer.android.com/guide/topics/ui/how-android-draws.html
- Android: addView and layout method does not work together
- Android-layout does not work properly
- Android Studio does not show layout preview
- Set the absolute position of a view
- https://www.tabnine.com/code/java/methods/android.view.View/setBottom
 
    