|
有些页面中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;
}
} |
----------------------------
原文链接:https://blog.51cto.com/120806872/1606199
程序猿的技术大观园:www.javathinker.net
[这个贴子最后由 flybird 在 2020-04-08 10:09:27 重新编辑]
|
|