分類: android應用開發2013-12-19 09:40 1045人閱讀 評論(3) 收藏 舉報
1、前言
從谷歌那里找到的ScrollView嵌套ListView只顯示一行的解決辦法相信很多人都遇到過,然后大部分都是用這位博主的辦法解決的吧
剛開始我也是用這個辦法解決的,首先感謝這位哥的大私奉獻,貼上地址
http://blog.csdn.net/p106786860/article/details/10461015
2、解決的核心代碼
- public void setListViewHeightBasedOnChildren(ListView listView) {
- // 獲取ListView對應的Adapter
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- return;
- }
- int totalHeight = 0;
- for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
- // listAdapter.getCount()返回數據項的數目
- View listItem = listAdapter.getView(i, null, listView);
- // 計算子項View 的寬高
- listItem.measure(0, 0);
- // 統計所有子項的總高度
- totalHeight += listItem.getMeasuredHeight();
- }
- ViewGroup.LayoutParams params = listView.getLayoutParams();
- params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
- // listView.getDividerHeight()獲取子項間分隔符占用的高度
- // params.height最后得到整個ListView完整顯示需要的高度
- listView.setLayoutParams(params);
- }
但是這個代碼里面有一個問題,就是這個當你的ListView里面有多行的TextView的話,ListView的高度就會計算錯誤,它只算到了一行TextView的高度,
這個問題在so上的概述為以下:
http://stackoverflow.com/questions/14386584/getmeasuredheight-of-textview-with-wrapped-text
3、終極解決辦法
這個問題頭疼了一陣后,查找了一下,應該重寫一個TextView的onMeasure方法比較好解決
代碼有
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- Layout layout = getLayout();
- if (layout != null) {
- int height = (int)FloatMath.ceil(getMaxLineHeight(this.getText().toString()))
- + getCompoundPaddingTop() + getCompoundPaddingBottom();
- int width = getMeasuredWidth();
- setMeasuredDimension(width, height);
- }
- }
- private float getMaxLineHeight(String str) {
- float height = 0.0f;
- float screenW = ((Activity)context).getWindowManager().getDefaultDisplay().getWidth();
- float paddingLeft = ((LinearLayout)this.getParent()).getPaddingLeft();
- float paddingReft = ((LinearLayout)this.getParent()).getPaddingRight();
- //這里具體this.getPaint()要注意使用,要看你的TextView在什么位置,這個是拿TextView父控件的Padding的,為了更准確的算出換行
- int line = (int) Math.ceil( (this.getPaint().measureText(str)/(screenW-paddingLeft-paddingReft))); height = (this.getPaint().getFontMetrics().descent-this.getPaint().getFontMetrics().ascent)*line; return height;}
上面的代碼完成更能為,在ListView開始測量時,測量到TextView時,就調用我們的onMeasure方法,我們就可以測量字體的總寬度除與去掉邊距的屏幕的大小,就可以算出文字要幾行來顯示,然后測量字體的高度*行數可以得到字體的總高度,然后在加上上下邊距就是TextView真正的高度,然后setMeasuredDimension進去就可以計算出正確的值出來。