The ViewTreeObserver listener has not been invoked after some time

The ViewTreeObserver listener has not been invoked after some time… here is a solution to the problem.

The ViewTreeObserver listener has not been invoked after some time

I’m having a lot of trouble with ViewTreeObserver. Everything works fine for an unpredictable period of time, and then the listener is no longer running. This must be because the documentation says: The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View
So I redo the settings every time I change the View:

   protected void shrinkToFit(final TextView t) {
    if(vto==null||!vto.isAlive()){
    vto = t.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            doAdjust(t);
        }
    });
    }
}

Here’s how I call it:

TextView t = (TextView) findViewById(R.id.maindesc);

                t.setTextSize(Constants.MAINDESC_SIZE);

                String todisp_1 = tarifreadtemp.area_desc + ":"
                        + tarifreadtemp.area_tarifuserdesc;
                shrinkToFit(t);
                t.setText(todisp_1);
                t.invalidate();

Best Solution

Normally, I add addOnGlobalLayoutListener a listener to my View before redrawing or changing the layout (this can happen when I first initialize the View or maybe before changing its layout), and the first thing I do in a listener is remove the listener from the View.

Related Problems and Solutions