问题
Currently I have a button that loads an activity.
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.
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).
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.
Current relevant code:
@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.
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.
回答1:
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);
}
来源:https://stackoverflow.com/questions/41268495/wait-for-activity-to-display