今天遇到问题如题:
最后通过网络找到答案,,,主要是ScrollView问题,,,所以贴出来大家一起共同学习.
解决方法1:(代码去计算高度,然后在显示)
private void setListViewHeightBasedOnChildren(ListView listView) {
ItemListAdapter listAdapter = (ItemListAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
解决方法2: (复写listView )
public void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { |
2 | int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2 , MeasureSpec.AT_MOST); |
3 | super .onMeasure(widthMeasureSpec, mExpandSpec); |
4 |
5 | } |
public class NewTextView extends TextView {
private Context context;
public NewTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
}
public NewTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
}
@SuppressLint("FloatMath")
@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) FloatMath.ceil(getMaxLineHeight(this.getText()
.toString()))
+ getCompoundPaddingTop()
+ getCompoundPaddingBottom();
int width = getMeasuredWidth();
setMeasuredDimension(width, height);
}
}
@SuppressLint("NewApi")
private float 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))) +1 ; //+1是为了让界面更好看
height = (this.getPaint().getFontMetrics().descent - this.getPaint()
.getFontMetrics().ascent) * line;
return height;
}
}
float paddingReft = ((LinearLayout) this.getParent()).getPaddingRight();