编辑:遗憾的是,它不适用于 Actionbarsherlock 和 Compatibility Package 中的 ListFragment。出于某种原因,上边距被添加到下边距。左右边距在 LayoutListener 内工作正常。
在Android 开发者示例中找到了解决此问题的方法
// Attach a GlobalLayoutListener so that we get a callback when the layout
// has finished drawing. This is necessary so that we can apply top-margin
// to the ListView in order to dodge the ActionBar. Ordinarily, that's not
// necessary, but we've set the ActionBar to "overlay" mode using our theme,
// so the layout does not account for the action bar position on its own.
ViewTreeObserver observer = getListView().getViewTreeObserver();
observer.addOnGlobalLayoutListener(layoutListener);
// Because the fragment doesn't have a reliable callback to notify us when
// the activity's layout is completely drawn, this OnGlobalLayoutListener provides
// the necessary callback so we can add top-margin to the ListView in order to dodge
// the ActionBar. Which is necessary because the ActionBar is in overlay mode, meaning
// that it will ordinarily sit on top of the activity layout as a top layer and
// the ActionBar height can vary. Specifically, when on a small/normal size screen,
// the action bar tabs appear in a second row, making the action bar twice as tall.
ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int barHeight = getActivity().getActionBar().getHeight();
ListView listView = getListView();
FrameLayout.LayoutParams params = (LayoutParams) listView.getLayoutParams();
// The list view top-margin should always match the action bar height
if (params.topMargin != barHeight) {
params.topMargin = barHeight;
listView.setLayoutParams(params);
}
// The action bar doesn't update its height when hidden, so make top-margin zero
if (!getActivity().getActionBar().isShowing()) {
params.topMargin = 0;
listView.setLayoutParams(params);
}
}
};