Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewTreeObserver Listener not called after some time

Tags:

java

android

I have great difficulties when using ViewTreeObserver. All works fine for some unpredictable period of time, and then the listener is not operational anymore. It is certainly because of what is written in the doc:The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View Therefore i redo the setup every time I change my view:

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

and here's how I invoke 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();
like image 288
michaelsmith Avatar asked Nov 04 '22 05:11

michaelsmith


2 Answers

Usually I add the addOnGlobalLayoutListener listener to my views before the layout gets redrawn or changed(this could happen when I first init the view or maybe before changing its layout) and in the listener the first thing that I do is to remove the listener from the view.

like image 138
Cata Avatar answered Nov 10 '22 15:11

Cata


I encountered a similar problem where sometimes the onGlobalLayout was not called. This happened, sometimes, when rotating the device and the listview was redrawn.

MY SOLUTION

My solution to the problem was as follows: I noticed that no matter what, the onScroll listener was called each time the listview was redrawn. So I set a global flag when I register the onGlobalLayout listener, and moved all the code from the listener to a separate function.

If the listener was called I called that function and reset the flag.

Otherwise, each time onScroll was called I checked the status of the flag, and if it was still true then I called that function and reset the flag.

like image 29
Zvi Avatar answered Nov 10 '22 15:11

Zvi