天天看点

ScrollView与ListView的事件冲突

布局文件

当ListView嵌套在ScrollView中时,会发生冲突,导致ListView控件的拉动效果消失‘

解决办法:

重写ListView的onTouchEvent(),并在返回前调用getParent().requestDisallowInterceptTouchEvent(true)  表示。不允许父层拦截或干扰本控件

Demo

ScrollView与ListView的事件冲突
ScrollView与ListView的事件冲突

1 package com.xqx.fight;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.view.Menu;
 6 import android.view.MotionEvent;
 7 import android.view.View;
 8 import android.view.View.OnTouchListener;
 9 import android.widget.ArrayAdapter;
10 import android.widget.ListView;
11 
12 public class MainActivity extends Activity {
13 
14     private ListView listView;
15     private ArrayAdapter<String > adapter;
16     
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21         
22         listView = (ListView) findViewById(R.id.listView);
23         adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
24         for(int i=0;i<20;i++)
25         {
26             adapter.add("列表项:"+i);
27         }
28         listView.setAdapter(adapter);
29         
30         listView.setOnTouchListener(new OnTouchListener() {
31             
32             @Override
33             public boolean onTouch(View v, MotionEvent event) {
34                 //getParent().requestDisallowInterceptTouchEvent(true)  不允许父层拦截或干扰本控件
35                 listView.getParent().requestDisallowInterceptTouchEvent(true);
36                 return false;
37             }
38         });
39     }
40 
41 }      

MainActivity.class

ScrollView与ListView的事件冲突
ScrollView与ListView的事件冲突
1 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     
 6    >
 7    
 8     
 9     <LinearLayout 
10         android:layout_width="match_parent"
11         android:layout_height="match_parent"
12         android:orientation="vertical"
13         >
14         
15         <TextView android:layout_width="match_parent"
16             android:background="#5000"
17             android:layout_height="100dp"
18             android:text="上面部分"/>
19         
20     <ListView 
21         android:layout_width="match_parent"
22         android:layout_height="250dp"
23         android:id="@+id/listView"
24         >
25     </ListView>
26         
27         <TextView android:layout_width="match_parent"
28             android:layout_height="100dp"
29             android:background="#5000"
30             android:text="底部部分"/>
31         
32         
33     </LinearLayout>
34     
35     
36 
37 </ScrollView>      

activity_main.xml

效果图:

ScrollView与ListView的事件冲突

继续阅读