溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android ListView高度問題

發(fā)布時間:2020-06-07 11:27:59 來源:網(wǎng)絡(luò) 閱讀:2249 作者:focus_000 欄目:移動開發(fā)

有些頁面中ListView只是整個頁面的一小部分,需要上下滑動整個頁面,ListView不讓自己滑動,默認ListView只會顯示第一個item。這個時候需要重新設(shè)置一下ListView的高度。如果ListView的item中有TextView并且TextView的行數(shù)大于1行,這個時候.重設(shè)ListView的高度卻計算不出TextView的高度,會出現(xiàn)TextView只顯示一行的情況。這個時候需要使用自定義的TextView,并且不要設(shè)置MaxLines這個屬性。

設(shè)置ListView高度的代碼:

public   static void SetHeigth(ListView list) {
        ListAdapter listAdapter = list.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            View listItem = listAdapter.getView(i, null, list);
            //             listItem.measure(LinearLayout.LayoutParams.MATCH_PARENT,0);
            listItem.measure(0,0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = list.getLayoutParams();
        params.height = totalHeight+ (list.getDividerHeight() * (listAdapter.getCount() - 1));
        list.setLayoutParams(params);
    }

 自定義TextView的代碼:

public class MyTextView extends TextView {
    private Context context;
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        this.context=context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Layout layout = getLayout();  
        if (layout != null) {  
            int height = (int)Math.ceil(getMaxLineHeight(this.getText().toString()))  
                    + getCompoundPaddingTop() + getCompoundPaddingBottom();  
            int width = getMeasuredWidth();              
            setMeasuredDimension(width, height);  
        }  
    }
    private float getMaxLineHeight(String str){  
        float height = 0.0f;  
        float screenW = context.getResources().getDisplayMetrics().widthPixels;  
        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;
    }  
}


向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI