Skip to content Skip to sidebar Skip to footer

Getting Bitmap From Textlayout In Oncreate

I am able to convert a Layout with a TextView into a Bitmap, as long as the event that happens after onCreate(). But when I try during on create, it does not work. Is there a way

Solution 1:

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

So, something like this:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    finalViewTreeObserverviewTreeObserver= findViewById(sampleRelativeLayout).getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() {
        @OverridepublicvoidonGlobalLayout() {
        viewTreeObserver.removeOnGlobalLayoutListener(this);
        replaceTheRobot();
        }
    });
}

Solution 2:

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:

finalViewTreeObserverviewTreeObserver= findViewById(sampleRelativeLayout).getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() {
        @OverridepublicvoidonGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                findViewById(sampleRelativeLayout).getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                findViewById(sampleRelativeLayout).getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            replaceTheRobot();
        }
    });

Post a Comment for "Getting Bitmap From Textlayout In Oncreate"