package com.example.scrollviewlistview;
import android.app.Activity; import android.os.Bundle; 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.Button;
public class MainActivity extends Activity { private MyListView lv; @SuppressWarnings("unused") private Button change; String[] books = {"A语言","B语言","C语言","D语言","E语言","A1语言","B1语言","C1语言","D1语言","E1语言","A2语言","B2语言","C2语言","D2语言","E2语言","A2语言","B2语言","C语言","D语言","E语言"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setListViewHeightBasedOnChildren(lv); lv.getParent().requestDisallowInterceptTouchEvent(false); }
private void init() { // TODO Auto-generated method stub lv = (MyListView) findViewById(R.id.lv); change = (Button) findViewById(R.id.change); //配置数据 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, books); lv.setAdapter(adapter); } //根据listview的数据来计算他的应得的高度,设置高度 @SuppressWarnings("deprecation") public void setListViewHeightBasedOnChildren(MyListView listView) { @SuppressWarnings("rawtypes") ArrayAdapter listAdapter = (ArrayAdapter) 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(); int h = getWindowManager().getDefaultDisplay().getHeight(); if(params.height > h/2){ params.height = h/2; } listView.setLayoutParams(params); } }
|
|