如何从Runnable更新UI? [英] How to update UI from a Runnable?

查看:57
本文介绍了如何从Runnable更新UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从runnable更新ui.我的逻辑如下.我从片段生命周期的onCreate开始运行.而可运行实例负责请求网络.问题是可运行实例从网络中获取数据后,我不知道如何更新片段.

I need to update ui from runnable. My logic goes like below. I start the runnable from onCreate of the fragment lifecycle. And the runnable instance is responsible to request network. The problem is I don`t know how to update the fragment after runnable instance fetched the data from network.

代码以在CustomFragment.java中的片段中开始运行.

code to start runnable in fragment in CustomFragment.java.

public void onCreate(Bundle savedInstanceState) {
    Log.d(DEBUG_TAG, "onCreate");
    super.onCreate(savedInstanceState);

    accountMgr.requestAccountInfo();

}

代码在AccountManager.java中开始可运行

code to start runnable in AccountManager.java

/**
 * request Account info from server
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void requestAccountInfo() {
    Account act = getCurrentAccount();
    Thread t = new Thread(new RequestAccountInfoTask(act));
    t.start();
}

/**
 * automatically update Account info, like space usage, total space size, from background.
 */
 class RequestAccountInfoTask implements Runnable {

    private Account account;

    public RequestAccountInfoTask(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);

    }
}

推荐答案

runOnUiThread()需要 Activity 参考.还有其他选择.您不需要 Activity 对您的 Thread 的引用.您始终可以通过主循环程序获取UI处理程序.传递其他参数(例如您的界面)以在任务完成时更新片段.

runOnUiThread() requires Activity reference. There are alternatives. You don't need Activity reference to your Thread. You can always get UI handler with the main looper. Pass other arguments like your interface to update the fragment upon completion of your task.

class RequestAccountInfoTask implements Runnable {

    private Account account;
    private Handler mHandler;
    public RequestAccountInfoTask(Account account) {
        this.account = account;
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void run() {
        doRequestAccountInfo(account);
        //use the handler
    }
}

您在实例化的 Handler 上运行的所有内容都将位于UI线程上.

Anything you run on the instantiated Handler will be on UI thread.

当然,使用 runOnUiThread()是完全合理的.

Of course, using runOnUiThread() is totally reasonable.

这篇关于如何从Runnable更新UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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