Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Change TextView text from another class

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()

like image 378
jkigel Avatar asked Jun 09 '26 10:06

jkigel


2 Answers

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);    
                }
            });
        }
    }
like image 150
Chintan Raghwani Avatar answered Jun 11 '26 00:06

Chintan Raghwani


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.

like image 25
micha Avatar answered Jun 11 '26 00:06

micha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!