4

The docs for the setContentView() method in the Activity class state that the view is added to the activity window AND inflated. However, the width and height of the root view are both zero after setContentView() is called.

Example below:

Activity class

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "myTag";

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

        View root = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        // Here I expect the root view to have been inflated and have a width and height
        Log.i(TAG, "Root view width:" + root.getWidth() + " height:" + root.getHeight());
    }
}

Layout XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_gravity="center_horizontal|center_vertical" />

</FrameLayout>

My problem is I need to create a bitmap image of the root view upon the launch of the activity and I'm not sure when I should do this that guarantees the root view has been inflated.

Onik
  • 19,396
  • 14
  • 68
  • 91
chips
  • 160
  • 1
  • 10
  • 2
    [Why does calling getWidth() on a View in onResume() return 0?](https://stackoverflow.com/q/22972022/3290339) – Onik Mar 22 '19 at 17:34
  • Possible duplicate of [Why does calling getWidth() on a View in onResume() return 0?](https://stackoverflow.com/questions/22972022/why-does-calling-getwidth-on-a-view-in-onresume-return-0) – Taslim Oseni Mar 22 '19 at 18:47

1 Answers1

3

As @Onik correctly commented, he has already answered my question here Why does calling getWidth() on a View in onResume() return 0?

I would add that you could also attach an addOnLayoutChangeListener to your view and remove it in onLayoutChange(). It's ugly, but seems to be the only way;

Onik
  • 19,396
  • 14
  • 68
  • 91
chips
  • 160
  • 1
  • 10