Reputation: 333
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);
}
});
}
Upvotes: 1
Views: 2678
Reputation: 67502
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.
Upvotes: 3