有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java安卓:向线程传递参数

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

汇编错误:

线

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) 个答案

  1. # 1 楼答案

    您需要将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)。但是上面的内容应该可以修复您遇到的错误