第一种自定义ListView
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, height);
}
}
第二种,在代码里面进行重新测量
public class MainActivity extends Activity {
private ListView lv;
private List<String> list;
private int hight;
private ArrayAdapter listAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
inData();
setLv();
}
private void setLv() {
listAdapter = (ArrayAdapter) lv.getAdapter();
if(listAdapter!=null){
for (int i = 0; i < listAdapter.getCount(); i++) {
View item = listAdapter.getView(i, null, lv);
item.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 40));
item.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
hight+=item.getMeasuredHeight();
}
LayoutParams params = lv.getLayoutParams();
params.height=hight+lv.getDividerHeight()*(listAdapter.getCount()-1)+lv.getPaddingTop()+lv.getPaddingBottom();
int h=getWindowManager().getDefaultDisplay().getHeight();
if(params.height>h/2){
params.height=h/2;
}
lv.setLayoutParams(params);
}
}
private void inData() {
list = new ArrayList<String>();
for (int i = 0; i < 30; i++) {
list.add("这里是item"+i);
}
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, list));
lv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()!=MotionEvent.ACTION_UP){
lv.getParent().requestDisallowInterceptTouchEvent(true);
}else{
lv.getParent().requestDisallowInterceptTouchEvent(false);
}
return false;
}
});
}
}