我正在查看 ListActivity
源代码,我看到正在定义一个私有(private)的 Handler
,还有一个 Runnable
在 onContentChanged()
方法中发布到此处理程序。
我不太明白这一点,因为据我所知,处理程序用于线程间通信。在这里,处理程序的定义和发布发生在同一个线程上,并且在 post() 调用中没有指定延迟。我也看不到处理程序被用于其他任何事情。
我可能误解了这里处理程序的使用。为什么按这里的方式完成,而不是直接运行 mList.focusableViewAvailable()
(在 runnable 中调用)?结果不一样吗?
下面是我认为是 ListActivity
源代码的相关部分:
public class ListActivity extends Activity {
protected ListView mList;
private Handler mHandler = new Handler();
private Runnable mRequestFocus = new Runnable() {
public void run() {
mList.focusableViewAvailable(mList);
}
};
/**
* Updates the screen state (current list and other views) when the
* content changes.
*
* @see Activity#onContentChanged()
*/
@Override
public void onContentChanged() {
super.onContentChanged();
View emptyView = findViewById(com.android.internal.R.id.empty);
mList = (ListView)findViewById(com.android.internal.R.id.list);
if (mList == null) {
throw new RuntimeException(
"Your content must have a ListView whose id attribute is " +
"'android.R.id.list'");
}
if (emptyView != null) {
mList.setEmptyView(emptyView);
}
mList.setOnItemClickListener(mOnClickListener);
if (mFinishedStart) {
setListAdapter(mAdapter);
}
mHandler.post(mRequestFocus);
mFinishedStart = true;
}
}
最佳答案
Why is it done the way it is here, and not by just running mList.focusableViewAvailable() (the call inside the runnable) directly? Wouldn't the result be the same?
您的关注点不应该是 Handler
。您应该关注对 post()
的调用。 Handler
甚至不是真正需要的,因为 post()
在 View
上可用——不过,这段代码可能早于它。
post()
获取一个 Runnable
并将其放入主应用程序线程的消息队列中。因此,在该队列中当前的所有其他消息都得到处理 (FIFO) 之前,它不会得到处理。据推测,ListActivity
需要先处理队列中的一些其他消息,然后 focusableViewAvailable()
才能成功运行。
关于android - 了解 ListActivity 中的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4979172/