Search code examples
androidandroid-relativelayout

RelativeLayout.getWidth returning 0 when layout width is 720


I'm trying to learn the basics of android and when I call RelativeLayout.getWidth I get 0 as a value instead of the expected size of the layout.

I have a RelativeLayout filling my screen:

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/activity_one>
   <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test"
        android:id="@+id/test"/>
    </RelativeLayout >

But when I use the code below in the oncreate(), I get 0 instead of the expected screen width 720.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);

        RelativeLayout rl= (RelativeLayout) findViewById(R.id.activity_one);

        TextView tempTextview = (TextView) findViewById(R.id.test);

        tempTextview.setText("W: " + rl.getWidth() + " - H:" + rl.getHeight());
}

I must be doing a very stupid mistake but I can't see what.


Solution

  • You should get width here when Your UI has been loaded and then only width can be invoked of layout.:

    @Override
     public void onWindowFocusChanged(boolean hasFocus) {
    
      super.onWindowFocusChanged(hasFocus);
    //paste your code to get your layout params.
     }