Reputation: 1592
I have a TextView
in MainActivity
, I would like to change the TextView
text within another class.
How can I access TextView
in MainActivity
from another class?
I tried the following
TextView textView = (TextView) findViewById(R.id.myTextView);
textView.setText("Text");
But the app crashes when calling setText()
Upvotes: 3
Views: 12103
Reputation: 3370
You have to use runOnUiThread(new Runnable()...
See following:
import android.content.Context;
private class AnotherClass {
protected MainActivity context;
public AnotherClass(Context context){
this.context = (MainActivity) context;
}
public void updateTV(final String str1){
context.runOnUiThread(new Runnable() {
@Override
public void run() {
context.textView.setText(str1);
}
});
}
}
Upvotes: 9
Reputation: 49552
If you want to update the text of the TextView a possible way would be to edit the text in a common data model that is shared by your classes. If onResume
from the activity is called later it can read the new value from the model and update the TextView.
Upvotes: 2
Reputation: 13541
I would recommend to use a handler to update the content of that Activity. This is only one way, there is multiple ways to do this.
The entire purpose of a handle is to have some background process/thread passing information into the UI thread.
Upvotes: 1