ScrollView + Listview 實現方案優選

來源:互聯網
上載者:User

標籤:listview   scrollview   

 

一,按

在開發中,最近常遇到這個UI的結構,遇到了不少問題,如下:

1, listview的高度不對

2, 頁面閃動,不在最開始的位置

3, 如果listview的item需要改變高度,listview的高度不能正常更新

 

二,解決方案一:動態計算listview高度

1, 具體函數請百度之,原理就是item高度加上divider高度

2, 局限:

2-1 使用麻煩,需要listview可能改變的地方調用

2-2 頁面在部分機型上,仍然存在閃動的問題

3, 參考代碼如下:

 

public void setListViewHeightBasedOnChildren(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();             }               System.out.println("aaa==="+totalHeight);           ViewGroup.LayoutParams params = listView.getLayoutParams();             params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));             listView.setLayoutParams(params);        }

三,解決方案二:使用自訂Listview

1, 使用自訂ListView,修改onMeasure()方法即可

參考代碼如下:

 

public class InScrollListView extends ListView{public InScrollListView(Context context) {super(context);}public InScrollListView(Context context, AttributeSet attrs) {super(context, attrs);}public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);}}

2, 局限:

2-1 頁面在部分機型上,仍然存在閃動的問題

2-2 如果有點擊事件需要修改item的高度,則需要wapper一層,具體實現方式就是將item是否是展開的狀態,包在資料結構中。點擊事件之後,update data,然後再notify adapter

 

四,解決方案三:利用Listview的Header (推薦方案)

1, 拆解頁面view,採用addHeader(View v)的方法將view加到listview中去。

2, 局限:

2-1 相對麻煩一些,但是實現效果是最好的。另外一個優點是,魅族機器上,scrollview滑動會有很奇怪的問題,換成Listview之後,也不存在這個問題。

本文出自 “小新專欄” 部落格,請務必保留此出處http://mikewang.blog.51cto.com/3826268/1553118

ScrollView +   Listview 實現方案優選

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.