的Andr​​oid / Java的:从另一个类变化有何看法? [英] Android/Java: Change view from another class?

查看:99
本文介绍了的Andr​​oid / Java的:从另一个类变化有何看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两班。 MainActivity,我在其中设置视图,并ClassX从中我要更新MainActivity视图。 ClassX是MainActivity称为AsyncTask的,如果这是相关的。

There are two classes. MainActivity, in which i set the view, and ClassX from which i want to update a view in MainActivity. ClassX is an AsyncTask called from MainActivity, if that's relevant.

我想要做的是改变一个叫mainTextLog视图的文本。我宣布一个全局变量的TextView,并在onCreate()方法使用我findViewById()。将其设置为视图

What i want to do is to change the text of a view called mainTextLog. I've declared a global TextView variable, and in the onCreate() method i set it to the view using findViewById().

private TextView logger;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    logger = (TextView) findViewById(R.id.mainTextLog);

}

现在我应该能够改变从OnCreate()中的文字,我可以。但因为我想将它从另一个类(ClassX)改变,我需要为它创建一个方法:

By now i should be able to change the text from onCreate(), and i can. But since i want to change it from another class (ClassX) i need to create a method for it:

public void setLogText(String text) {
    logger.setText(text);
}

但它不工作。我试着做记录和setLogText()方法静态的,但它仍然无法正常工作。该应用程序崩溃只是

But it doesn't work. I've tried making logger and the setLogText() method static, but it still doesn't work. The app just crashes.

这可能是pretty容易,但我的想法。

It's probably pretty easy, but i'm out of ideas.

推荐答案

如果您使用的是AsyncTask的你需要在任何 onProgressUpdate 或在 onPostExecute

If you are using an AsyncTask you need to set the value in either onProgressUpdate or in onPostExecute.

您真的应该阅读 AsyncTasks

您的不能更新从doInBackground方法的用户界面,因为它不是在UI线程运行,将会给你一个例外。

You CANNOT update the UI from the doInBackground method as it is not run in the UI thread and will give you an exception.

此外,你应该当应用程序崩溃,所以我们有一个更好的想法是什么问题后,你所得到的例外。但我猜你尝试更新从错误的线程中的文本。

Also, you should post the exception you are getting when the application crashes so we have a better idea what the problem is. But I'd guess you are trying to update the text from the wrong thread.

这篇关于的Andr​​oid / Java的:从另一个类变化有何看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆