Genia S. Genia S. - 4 months ago 46
Android Question

Is there a way to pass parameters to a Runnable?

I have a thread that uses a handler to post a runnable instance. it works nicely but I'm curious as to how I would pass params in to be used in the Runnable instance? Maybe I'm just not understanding how this feature works.

To pre-empt a "why do you need this" question, I have a threaded animation that has to call back out to the UI thread to tell it what to actually draw.

Answer

Simply a class that implements Runnable with constructor that accepts the parameter can do,

public class MyRunnable implements Runnable {
  private Data data;
  public MyRunnable(Data _data) {
    this.data = _data;
  }

  @override
  public void run() {
    ...
  }
}

You can just create an instance of the Runnable class with parameterized constructor.

MyRunnable obj = new MyRunnable(data);
handler.post(obj);
Comments