等待活动显示 [英] Wait for activity to display

查看:55
本文介绍了等待活动显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个加载活动的按钮.

Currently I have a button that loads an activity.

该活动中有一个 ListView,无论出于何种原因,它都需要相当长的时间来加载(不是等待数据,数据已经在内存中).问题在于,在呈现列表时,UI 会等待按钮被点击的位置,并且在列表完全加载之前不会更改屏幕.

That activity has a ListView in it that for whatever reason takes a fairly long time to load(not waiting for data, the data is already in memory). The problem is that while it's rendering the list, the UI is waiting where the button was clicked, and doesn't change screen until the list has fully loaded.

我想要的是,仅在加载 Activity 后才显示列表,因此至少在他们按下按钮时会发生一些事情(响应式 UI 很重要).

What I'd like, is to only display the list once the activity is loaded, so at least something happens as soon as they press the button(responsive UI is important).

目前,我对此的解决方法是生成一个线程,等待 50 毫秒,然后为我的列表设置适配器(使用 runOnUiThread).当然,如果在某些手机上加载 Activity 的时间超过 50 毫秒,则必须加载整个列表才能再次加载该 Activity.

Currently, my hack around solution to this, is to spawn a thread, wait for 50 milliseconds, and then set the adapter for my list(using runOnUiThread). Of course, if the activity takes longer than 50ms to load on some phones, then it'll have to load the entire list to load the activity again.

当前相关代码:

@Override
public void onPostResume() {
    super.onPostResume();
    new Thread(new Runnable() {
        @Override
        public void run() {
            final AdapterData data = getData();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    myAdapter = new MyAdapter(MyActivity.this, data);
                    lvMyList.setAdapter(myAdapter);
                }
            });
        }
    }).start();
}

我只是在代码中更改了变量名称,但这无关紧要.这只是为了您可以看到我的一般解决方案.

I just changed variable names in the code, but that's not relevant. This is just so you can see my general solution.

我觉得应该在活动完成创建时调用某种回调.我认为 onPostResume 等待活动完成加载,但这不起作用.还是挂了.

I feel like there should be some kind of callback that's called when the activity finishes creating. I thought that onPostResume waited for the activity to finish loading, but that did not work. It still hung.

推荐答案

你可以使用 IdleHandler

you can use IdleHandler

protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.xxx);  
    final AdapterData data = getData();
    IdleHandler handler = new IdleHandler() {  

        @Override  
        public boolean queueIdle() {  
            myAdapter = new MyAdapter(MyActivity.this, data);
            lvMyList.setAdapter(myAdapter);
            return false;  
        }   
    };  
    Looper.myQueue().addIdleHandler(handler);  

}  

这篇关于等待活动显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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