我怎么能传递一个对象在一个按钮侦听匿名生成一个新的线程 [英] How can i pass an object to a new thread generated anonymously in a button listener
问题描述
我想一个对象(案卷用于打印)传递到一个新的线程,它将打印案卷。我的code是:
I would like to pass an object (docket for printing) to a new thread which will print the docket. My code is:
private final Button.OnClickListener cmdPrintOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
enableTestButton(false);
Looper.prepare();
doConnectionTest();
Looper.loop();
Looper.myLooper().quit();
}
}).start();
}
};
我如何传递对象呢?
此外 - 我需要生成在UI线程对象,刚开始新的线程,所以我在这里可以把这个方法(例如getDocketObject())就我的code以下
How do I pass the object to it? Also - I need to generate the object in the UI thread, just before starting the new thread so where could I put this method (e.g. getDocketObject()) in relation to my code below
感谢,
安东
推荐答案
您可以创建自己的Runnable类实现:
You could create your own Runnable class implementation:
private class RunnableInstance implements Runnable {
protected Docket docket;
public void run() {
//do your stuff with the docket
}
public void setDocket(Docket docket) {
this.docket = docket;
}
}
然后用它来创建线程
And then use it to create the thread
public void onClick(View v) {
RunnableInstance target = new RunnableInstance();
target.setDocket(docketInstance);
new Thread(target).start();
}
如果您需要坚持一个匿名类你可以这样做:
If you need to stick to an anonymous class you could do:
public void onClick(View v) {
final Docket docket = docketInstance;
Runnable target = new Runnable(){
public void run() {
// do your stuff with the docket
System.out.println(docket);
}
};
new Thread(target).start();
}
但你必须确保你实例分配给最后一个变量。
But you have make sure you assign the instance to a final variable.
这篇关于我怎么能传递一个对象在一个按钮侦听匿名生成一个新的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!