Search code examples
androidviewrunnablemeasure

How to return a value from a method that needs to perform some operations inside a Runnable?


To get the width of a view when the Activity/Fragment is still measuring its views, you use a ViewTreeObserver or the View's post method with your own Runnable. I usually adopt de second one. But now -after some calculations, I would like to return the value, but because the method run doesn’t return any value (void), and I must way to measure the width of the view, I have come to a dead end. Has someone any idea?

Thanks!

int getDesiredWidth(final View view) {
    final int[]finalWidth = {0};

    view.post(new Runnable() {
        @Override
        public void run() {
            int width = view.getLayoutParams().width;
            //Calculate 'finalWidth' computing margins and other size's view
            return finalWidth[0]; //error: cannot return a value from a method with void type
        }
    });

    return finalWidth[0];
}

Solution

  • You will have to create a custom Interface to return a value from a different thread:

    public interface FooBar{
        public abstract void onCalculationFinished(int result);
    }
    

    Then create a custom Class that extends Runnable with an constructor you can pas an instance of your interface to:

    public class NameItHoweverYouLike extends Runnable{
        FooBar i;
        public NameItHoweverYouLike(FooBar interface){
            this.i = interface;
        }
        @Override
        public void run() {
            int width = view.getLayoutParams().width;
            //Calculate 'finalWidth' computing margins and other size's view
            if(i != null){
                i.onCalculationFinished(width);
            }
        }
    }
    

    Create a new Instance of this class and run in.