package com.bawei.day06_scrollview;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;public classMainActivity extends Activity {privateListView listView;private Listlist;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.listview);
list= new ArrayList();for (int i = 0; i < 200; i++) {
list.add(i+"");
}
BaseAdapter adapter=new Adper(MainActivity.this,list);
listView.setAdapter(adapter);
}//界面加载完
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
setListViewHeightBasedOnChildren(listView);
}
public void setListViewHeightBasedOnChildren(ListView listView) {
//BaseAdapter为listview布局
BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if(listItem != null){
listItem.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
listItem.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
+ listView.getPaddingTop() + listView.getPaddingBottom();
listView.setLayoutParams(params);
}
}