Is there a way to pass parameters to a Runnable? [duplicate]
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);
There are various ways to do it but the easiest is the following:
final int param1 = value1;final int param2 = value2;... new Runnable() { public void run() { // use param1 and param2 here }}
If you need to communicate information into a Runnable
, you can always have the Runnable
object constructor take this information in, or could have other methods on the Runnable
that allow it to gain this information, or (if the Runnable
is an anonymous inner class) could declare the appropriate values final
so that the Runnable
can access them.
Hope this helps!