简体   繁体   English

更新来自其他活动的主要活动值

[英]Update main activity values from a different activity

I want to update textview in my main activity view. 我想在主活动视图中更新textview。

I have main.xml file that contains the main application ascreen, in that screen, I have textview that I need to update from time to time from another activity (class). 我有一个main.xml文件,其中包含一个主应用程序屏幕,在该屏幕中,我有textview,我需要不时地从另一个活动(类)进行更新。

If I try to update those values from the main activity it work perfect, but when I'm trying to do it from deferent activity the application crashes. 如果我尝试从主要活动中更新这些值,则可以正常工作,但是当我尝试从不同活动中进行更新时,应用程序将崩溃。

Here is the method of the main activity, I need to know how to call it from the other activity. 这是主要活动的方法,我需要知道如何从其他活动中调用它。

Main Activity method: 主要活动方法:

    public void update_counters(){    
        TextView sms_textview = (TextView) findViewById(R.id.sms_textview);
        sms_textview.setText(String.valueOf(sms_missed));
    }

Please Help 请帮忙

Indeed it's a bad practice to have any static references to activities (or other contexts). 确实,对活动(或其他上下文)进行任何静态引用是一种不良做法。 Activity are designed to be rather independed from each other. 活动被设计为彼此独立。

You can receive a result from an activity that was started with startActivityForResult() method and than react appropriately. 您可以从以startActivityForResult()方法启动的活动中接收结果,然后做出适当的反应。

Like @Roman said, it's a bad practice to touch the UI stuff from other activities, and activities should be independent. 就像@Roman所说的那样,从其他活动中触摸UI内容是一种不好的做法,并且活动应该是独立的。 What you can do, is a little bit redesign your message passing method. 您可以做的是稍微重新设计您的消息传递方法。 One might be good is to use the broadcast receiver, it also guarantees a better extensibility of your program. 一个不错的办法是使用广播接收器,它还可以保证程序的更好扩展性。

So, whenever your 'other' activity need to call the update_counters, it turns to broadcast such an intent. 因此,每当您的“其他”活动需要调用update_counters时,它就会广播这种意图。 Your previous MainActivity should register to listen to that broadcast, and update the UI as necessary. 您以前的MainActivity应该注册以收听该广播,并根据需要更新UI。 What would be the best is you can have several more instance of that activity, or other activity that can register to that broadcast as well. 最好的办法是,您可以拥有该活动的多个实例,或者也可以注册该广播的其他活动。

Is there only one instance of your main activity? 您的主要活动只有一个实例吗? If so, store a static reference to it in the main activity class, initialize it in onCreate. 如果是这样,请将对它的静态引用存储在主活动类中,并在onCreate中对其进行初始化。 Then have a static method that uses that reference to get to the instance: 然后有一个使用该引用来访问实例的静态方法:

static MainActivity TheMainActivity;

static public void update_counters()
{
    TextView sms_textview = (TextView) TheMainActivity.findViewById(R.id.sms_textview); sms_textview.setText(String.valueOf(sms_missed));
}

The in the other activity: 在其他活动中:

MainActivity.update_counters();

This is called a singleton. 这称为单例。 Or, sometimes, a global. 或有时是全球性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM