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
nameasfinal, otherwise you can’t use it in an inner anonymous class.Additionally, you need to declare which
thisyou want to use; as it stands, you’re using theRunnableobject’sthisreference. What you need is something like this:However, I’m not sure this is the best way to update the UI (you should probably be using
runOnUiThreadandAsyncTask). But the above should fix the errors you’ve encountered.