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()
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);
}
});
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With