如何将上下文和名称字符串作为参数传递给新线程?
编译错误:
线
label = new TextView(this);
构造函数 TextView(new Runnable(){}) 未定义
行“label.setText(name);
”:
不能在不同方法中定义的内部类中引用非最终变量名
代码:
public void addObjectLabel (String name) {
mLayout.post(new Runnable() {
public void run() {
TextView label;
label = new TextView(this);
label.setText(name);
label.setWidth(label.getWidth()+100);
label.setTextSize(20);
label.setGravity(Gravity.BOTTOM);
label.setBackgroundColor(Color.BLACK);
panel.addView(label);
}
});
}
最佳答案
你需要声明name
为final
,否则你不能在内部anonymous class中使用它.
此外,您需要声明您要使用哪个this
;就目前而言,您正在使用 Runnable
对象的 this
引用。你需要的是这样的:
public class YourClassName extends Activity { // The name of your class would obviously be here; and I assume it's an Activity
public void addObjectLabel(final String name) { // This is where we declare "name" to be final
mLayout.post(new Runnable() {
public void run() {
TextView label;
label = new TextView(YourClassName.this); // This is the name of your class above
label.setText(name);
label.setWidth(label.getWidth()+100);
label.setTextSize(20);
label.setGravity(Gravity.BOTTOM);
label.setBackgroundColor(Color.BLACK);
panel.addView(label);
}
});
}
}
但是,我不确定这是更新 UI 的最佳方式(您可能应该使用 runOnUiThread
和 AsyncTask
)。但以上内容应该可以解决您遇到的错误。
关于java - Android:将参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11597708/