简体   繁体   中英

Android: passing arguments to threads

How can I pass the context and the name string as arguments to the new thread?

Errors in compilation:

Line

label = new TextView(this);

The constructor TextView(new Runnable(){}) is undefined

Line " label.setText(name); " :

Cannot refer to a non-final variable name inside an inner class defined in a different method

Code:

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

You need to declare name as final , otherwise you can't use it in an inner anonymous class .

Additionally, you need to declare which this you want to use; as it stands, you're using the Runnable object's this reference. What you need is something like 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);
            }
        });
    }
}

However, I'm not sure this is the best way to update the UI (you should probably be using runOnUiThread and AsyncTask ). But the above should fix the errors you've encountered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM