android listview,GridView 和 ScrollView

來源:互聯網
上載者:User

標籤:android listview   gridview   relativelayout   linearlayout   measure   

前段時間 遇到 listview 和scrollview 布局的問題 ,現在提供一個解決方案
if (listAdapter == null || listAdapter.getCount() == 0) {  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.clearFocus();

這個裡面有一個很重要的問題,在調用 listItem.measure(0, 0); 有些時候會報錯,根本原因在於 listitem 的布局;最外面布局採用 LinearLayout,在調用listItem.measure(0, 0)時,其實根本是調用 LinearLayout.measure 方法;同樣 RelativeLayout 布局也是一樣,但是,調用RelativeLayout .measure  方法 會報錯 。

解決辦法:

   1.listitem  布局最外層 用LinearLayout。

    2. listitem  布局最外層 依然採用 RelativeLayout  布局,自訂RelativeLayout  並重寫 onMeasure方法

@Overrideprotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){    int widthSize = MeasureSpec.getSize(widthMeasureSpec);          int heightSize = MeasureSpec.getSize(heightMeasureSpec);    // Restrict the aspect ratio to 1:1, fitting within original specified dimensions    int chosenDimension = Math.min(widthSize, heightSize);    widthMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);    heightMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);    getLayoutParams().height = chosenDimension;    getLayoutParams().width = chosenDimension;    super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }

android listview,GridView 和 ScrollView

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.