java Android 从另一个类更改 TextView 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11807609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:26:37  来源:igfitidea点击:

Android Change TextView text from another class

javaandroidandroid-activity

提问by jkigel

I have a TextViewin MainActivity, I would like to change the TextViewtext within another class.

我有一个TextViewin MainActivity,我想TextView在另一个班级中更改文本。

How can I access TextViewin MainActivityfrom another class?

如何访问TextViewMainActivity从另一个类?

I tried the following

我尝试了以下

TextView textView = (TextView) findViewById(R.id.myTextView);

TextView textView = (TextView) findViewById(R.id.myTextView);

textView.setText("Text");

textView.setText("文本");

But the app crashes when calling setText()

但是调用时应用程序崩溃 setText()

回答by Chintan Raghwani

You have to use runOnUiThread(new Runnable()...

你必须使用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);    
                }
            });
        }
    }

回答by micha

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 onResumefrom the activity is called later it can read the new value from the model and update the TextView.

如果您想更新 TextView 的文本,一种可能的方法是在您的类共享的公共数据模型中编辑文本。如果onResume稍后从活动中调用,它可以从模型中读取新值并更新 TextView。

回答by JoxTraex

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.

句柄的全部目的是让一些后台进程/线程将信息传递到 UI 线程中。