Android/Java: Change view from another class?

六眼飞鱼酱① 提交于 2019-12-25 08:09:03

问题


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.

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

}

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);
}

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.

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


回答1:


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

You really should read the documentation for AsyncTasks

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.




回答2:


I've done this plenty in the app im working on, its sort of an MDI type app on the android tablet.

To do what you're asking....

in MainActivity have

public static void setText(String txt){
  ((TextView)findViewById(R.id.mainTextLog)).setText(txt);
}

then in the child (or calling class) call it like...

MainActivity.setText("myTextToShow");

That's it... im using android api level 12... If i remember correcty it worked in api level 7 as well though.

Hope this helps...




回答3:


One possibility is that: when you call setLogText in another Class X. The MainActivity may not be existing anymore, which makes the logger a null reference?



来源:https://stackoverflow.com/questions/10677675/android-java-change-view-from-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!