Getting Bitmap from TextLayout in onCreate

懵懂的女人 提交于 2019-12-02 09:37:20

View is not rendered yet. You can use view.getViewTreeObserver().addOnGlobalLayoutListener to get notified when your layout is ready.

So, something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ViewTreeObserver viewTreeObserver = findViewById(sampleRelativeLayout).getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
        viewTreeObserver.removeOnGlobalLayoutListener(this);
        replaceTheRobot();
        }
    });
}

Building upon the user1779222 answer, if you wish to manage earlier Android releases, you can test run the very similarly named removeGlobalOnLayoutListener instead of removeOnGlobalLayoutListener. Also, to avoid the error java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again, you can get the observer again instead of using the original observer. With those changes, the result would be as follows:

    final ViewTreeObserver viewTreeObserver = findViewById(sampleRelativeLayout).getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                findViewById(sampleRelativeLayout).getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                findViewById(sampleRelativeLayout).getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            replaceTheRobot();
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!