【问题标题】:Android: Update current activity UI in HandlerAndroid:在处理程序中更新当前活动 UI
【发布时间】:2018-11-16 20:23:31
【问题描述】:

当处理程序在其他类中调用时,我无法更新活动中的 UI。下面是我创建的代码。

活动 A

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_A);

    Handler handler = new Handler(); //Here is where the handler is start, other class will update the Handler message.
    ......
}

活动 B

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_B);

    ......
}

//Just a dummy function called when handler is triggered
private void onChange(){
    TextView tv_status = findViewById(R.id.status);
    tv_status.setText("Complete");
}

类处理程序

public Handler {

    public Handler(){
         Handler handler = new Handler(){
               public void HandleMessage(Message msg){
                    switch (msg.what) {
                        case 1:
                             break;
                        case 2:
                             //should trigger to update the TextView in Activity B here
                             break;
                   }
              }
        };

        .......

    }
}

Activity A 为主,调用 Handler 启动 Handler,Activity B 只是更新 Handler 触发的 UI。

【问题讨论】:

  • 你的 Activity 是如何知道 Handler 存在的?你在哪里创建处理程序?
  • 要从处理程序更新任何视图,您需要更新主线程中的视图。
  • cricket_007。我的坏事业没有显示完整的步骤。我会更新我的问题。
  • 对不起兄弟,误会了,你需要先确定你在UI线程中
  • 希望此链接对您有所帮助-stackoverflow.com/questions/15685752/…

标签: android handler


【解决方案1】:

希望这会有所帮助。

public Handler {

    public Handler(){
         Handler handler = new Handler(){
               public void HandleMessage(Message msg){
                    switch (msg.what) {
                        case 1:
                             break;
                        case 2:
                             //should trigger to update the TextView in Activity A here 
                            runOnUiThread(new Runnable() {
                             @Override
                               public void run() {
                                 // Update your view
                               }
                              });
                             break;
                   }
              }
        };

        .......

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2013-08-02
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多