温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android ListView高度问题

发布时间:2020-06-07 11:27:59 来源:网络 阅读:2228 作者:focus_000 栏目:移动开发

有些页面中ListView只是整个页面的一小部分,需要上下滑动整个页面,ListView不让自己滑动,默认ListView只会显示第一个item。这个时候需要重新设置一下ListView的高度。如果ListView的item中有TextView并且TextView的行数大于1行,这个时候.重设ListView的高度却计算不出TextView的高度,会出现TextView只显示一行的情况。这个时候需要使用自定义的TextView,并且不要设置MaxLines这个属性。

设置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问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI