## 实现自定义的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
public boolean dispatchDragEvent(DragEvent event) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchDragEvent(event);
}
}
## 主界面中计算ListVIew宽高 ##
public class MainActivity extends Activity {
private String[] books = {"A语言","B语言","C语言","D语言","E语言","A1语言","B1语言","C1语言","D1语言","E1语言","A2语言","B2语言","C2语言","D2语言","E2语言","A2语言","B2语言","C语言","D语言","E语言"};
private ScrollView scroll;
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
scroll = (ScrollView) findViewById(R.id.scroll);
lv = (ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, books);
lv.setAdapter(adapter);
getListVeiwHeight(lv);
lv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
scroll.requestDisallowInterceptTouchEvent(true);
return false;
}
});
lv.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount) {
scroll.requestDisallowInterceptTouchEvent(false);
}
}
});
}
private void getListVeiwHeight(ListView listView) {
ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i=0; i<listAdapter.getCount(); i++) {
View item = listAdapter.getView(i, null, listView);
if (item != null) {
item.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
item.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
totalHeight += item.getMeasuredHeight();
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount()-1))
+ listView.getPaddingTop() + listView.getPaddingBottom();
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int screenHeight = metric.heightPixels;
if (params.height > screenHeight/2) {
params.height = screenHeight/2;
}
listView.setLayoutParams(params);
}
}