Listview和scrollView的冲突解决

来源:互联网 发布:画中画的软件 编辑:程序博客网 时间:2024/05/08 06:38

//Listview和scrollView的冲突解决    自定义listView 事件分发机制   阻止父层的View截获touch事件

//布局中com.zmy.d4_listview_scrollview.MyListView自定义的MyListView类的全路径名

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zmy.d4_listview_scrollview.MainActivity" >
           <LinearLayout
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical">
        
        <com.zmy.d4_listview_scrollview.MyListView
                  android:id="@+id/main_lv"
                  android:layout_width="match_parent"
                  android:layout_height="200dp">
            
        </com.zmy.d4_listview_scrollview.MyListView>
        
        <TextView
                 android:layout_width="match_parent"
                 android:layout_height="600dp"
                 android:textSize="30sp"
                 android:text=" 面朝大海,春暖花开"/>
    </LinearLayout>

    
</ScrollView>


 

mainActivity中

MyListView listView = (MyListView) findViewById(R.id.main_lv);

List<String> list=new ArrayList<String>();
        for (int i = 0; i <30; i++) {
            list.add("盟"+i);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item,R.id.textView1,list );
        listView.setAdapter(adapter);

//自定义ListView视图中

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;

public class MyListView extends ListView {

    public MyListView(Context context, AttributeSet attrs, int defStyle) {

        //自定义Listview重写三个构造方法

        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyListView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    //触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        return super.onTouchEvent(ev);
    }

    //事件分发
    //是否拦截   拦截true   不拦截false
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        return false;
    }
   
    //接受信息
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        //请求scrollview不拦截touch事件,因为scrollview也有滚动效果
        //可以阻止父层的View截获touch事件
        getParent().requestDisallowInterceptTouchEvent(true);
        return true;
    }


}
0 0
原创粉丝点击