天天看點

ScrollView+ListView沖突問題解決

問題1:ScrollView+ListView時,listView内容隻顯示一行:

解決:使用setListViewHeightBaseOnChildren,具體代碼如下:

private void setListViewHeightBaseOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
           

需要注意的一點是,此函數的調用時機。需要在給listview設定完adapter且adapter内容顯示完畢之後再調用有效。

若是在剛定義listview時調用,因為此時listview是空的,無任何内容,調用後仍然顯示一行。是以,簡單來說,就是要在給listview的adapter添加完資料後顯示時調用此函數;還有一種就是重寫listView,在使用listView時使用自定義的即可,重寫代碼如下:

public class ListViewForScrollView extends ListView {
    public ListViewForScrollView(Context context) {
        super(context);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs,
        int defStyle) {
        super(context, attrs, defStyle);
    }
        
    @Override
    /**
     * 重寫該方法,達到使ListView适應ScrollView的效果
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
           

問題2、進入ScrollView+listView界面時,不在界面頂部,顯示界面中間的問題:

原因:listview自動擷取了焦點;

解決:listView.setFocusable(false);這個隻要放在listview定義的地方即可。

繼續閱讀