Layout a view after resizing

Maragues picture Maragues · Oct 13, 2012 · Viewed 8.4k times · Source

I'm creating a grid that displays values that change very often. Because of this, I'm using a TextView that autoresizes when its content changes (Auto Scale TextView Text to Fit within Bounds). The resize takes place, but the view doesn't layout properly

layout after resize

The thing is, when I examine the activity with HierarchyViewer the layout displays as I want.

layout after hierarchyviewer

My guess is that HierarchyViewer invokes requestLayout() or invalidate() on the view, but I've tried that with no success. This code is invoked in the main activity with no effect.

new Handler().postDelayed(new Runnable() {            
            @Override
            public void run() {
              getWindow().getDecorView().requestLayout();
              getWindow().getDecorView().invalidate();
            }
          }, 5000);

I've also tried invalidating the view after resizing.

The TextView has gravity set to Center, and if no resize takes place, it looks ok.

Any hint will be welcome, thanks in advance!

Answer

Maragues picture Maragues · Oct 15, 2012

I solved it by overriding onLayout in one of the TextView's parent and using a Handler created in the constructor

public class CellView extends LinearLayout{
   public CellView(Context context) {
     super(context);

     mHandler = new Handler();

     View.inflate(context, R.layout.cellview, this);
  }

 @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    if(changed){
      mHandler.post(new Runnable() {          
        @Override
        public void run() {
          requestLayout();
        }
      });
    }

   super.onLayout(changed, left, top, right, bottom);
  }

I had tried calling requestLayout inside TextView's onLayout, tho it didn't work, I'm not sure why. It might be because the value was updated through an Observer, but the onTextChanged listener should happen in the UI Thread. I hope it serves someone else