Android開發————ListView內部Item高度設定
阿新 • • 發佈:2019-02-10
1、前言
從谷歌那裡找到的ScrollView巢狀ListView只顯示一行的解決辦法相信很多人都遇到過,然後大部分都是用這位博主的辦法解決的吧
剛開始我也是用這個辦法解決的,首先感謝這位哥的大私奉獻,貼上地址
2、解決的核心程式碼
- public void setListViewHeightBasedOnChildren(ListView listView) {
- // 獲取ListView對應的Adapter
- ListAdapter listAdapter = listView.getAdapter();
-
if (listAdapter
- 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上的概述為以下:
3、終極解決辦法
這個問題頭疼了一陣後,查找了一下,應該重寫一個TextView的onMeasure方法比較好解決
程式碼有
- @Override
- protectedvoid 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);
- }
- }
- privatefloat 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進去就可以計算出正確的值出來。