Android:将参数传递给线程

时间:2012-07-22 04:09:54

标签: java android multithreading

如何将上下文和名称字符串作为参数传递给新线程?

编译错误:

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);
        }
    });
}

1 个答案:

答案 0 :(得分:3)

您需要将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的最佳方式(您应该使用runOnUiThreadAsyncTask)。但是上面应该修复你遇到的错误。