Android ListView高度问题
有些页面中ListView只是整个页面的一小部分,需要上下滑动整个页面,ListView不让自己滑动,默认ListView只会显示第一个item。这个时候需要重新设置一下ListView的高度。如果ListView的item中有TextView并且TextView的行数大于1行,这个时候.重设ListView的高度却计算不出TextView的高度,会出现TextView只显示一行的情况。这个时候需要使用自定义的TextView,并且不要设置MaxLines这个属性。
设置ListView高度的代码:
publicstaticvoidSetHeigth(ListViewlist){ListAdapterlistAdapter=list.getAdapter();if(listAdapter==null){return;}inttotalHeight=0;for(inti=0,len=listAdapter.getCount();i<len;i++){ViewlistItem=listAdapter.getView(i,null,list);//listItem.measure(LinearLayout.LayoutParams.MATCH_PARENT,0);listItem.measure(0,0);totalHeight+=listItem.getMeasuredHeight();}ViewGroup.LayoutParamsparams=list.getLayoutParams();params.height=totalHeight+(list.getDividerHeight()*(listAdapter.getCount()-1));list.setLayoutParams(params);}
自定义TextView的代码:
publicclassMyTextViewextendsTextView{privateContextcontext;publicMyTextView(Contextcontext,AttributeSetattrs){super(context,attrs);//TODOAuto-generatedconstructorstubthis.context=context;}@OverrideprotectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){//TODOAuto-generatedmethodstubsuper.onMeasure(widthMeasureSpec,heightMeasureSpec);Layoutlayout=getLayout();if(layout!=null){intheight=(int)Math.ceil(getMaxLineHeight(this.getText().toString()))+getCompoundPaddingTop()+getCompoundPaddingBottom();intwidth=getMeasuredWidth();setMeasuredDimension(width,height);}}privatefloatgetMaxLineHeight(Stringstr){floatheight=0.0f;floatscreenW=context.getResources().getDisplayMetrics().widthPixels;floatpaddingLeft=((LinearLayout)this.getParent()).getPaddingLeft();floatpaddingReft=((LinearLayout)this.getParent()).getPaddingRight();//这里具体this.getPaint()要注意使用,要看你的TextView在什么位置,这个是拿TextView父控件的Padding的,为了更准确的算出换行intline=(int)Math.ceil((this.getPaint().measureText(str)/(screenW-paddingLeft-paddingReft)));height=(this.getPaint().getFontMetrics().descent-this.getPaint().getFontMetrics().ascent)*line;returnheight;}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。