1

We are creating a View programmatically in onCreate method and trying to set either of the following to that view-

  • The top and left or
  • The bottom and right.

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-

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Ashish
  • 77
  • 11
  • 1
    I have a question that you want to have 100 top-left margin to your `textview` . is it correct? – Mayur Gajra Jul 21 '21 at 15:43
  • 1
    @MayurGajra Thank you for the answer. As in web design `top` and `margin-top` work differently. I am expecting the same behavior here. When I get data to generate a design for android `margin` and `position (top, bottom, left, right)` both are treated differently. – Ashish Jul 22 '21 at 04:41

0 Answers0