问题
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.
回答1:
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);
回答2:
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
}
}
回答3:
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!
回答4:
Although you can use any of the above the answer, but if you question is really concerned about android then you can also use AsyncTask.
回答5:
I think a found a simpler approach:
public interface MyRunnable extends Runnable {
public void run(int data);
}
public void someMethod(int n, String s, MyRunnable r) {
...
r.run(n);
...
}
the call:
someMethod(5, "Hello", new MyRunnable() {
@Override
public void run(int data) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
}
});
来源:https://stackoverflow.com/questions/9123272/is-there-a-way-to-pass-parameters-to-a-runnable