通过dispatchTouchEvent解决ScrollView嵌套ListView滑动冲突问题

1,MainActivity

public class MainActivity extends Activity implements AdapterView.OnItemClickListener{


    private ListView listView;
    private ScrollView scrollView;
    private ArrayAdapterarrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        arrayAdapter=new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,getData());
        listView.setAdapter(arrayAdapter);

    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list_item);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        listView.setOnItemClickListener(this);
    }

    /***
     * 拦截事件,进行分发,分发到指定的对象
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_MOVE){
            listView.dispatchTouchEvent(event);
        }
        return super.dispatchTouchEvent(event);
    }

    public  List getData(){
        List list=new ArrayList();
        for(int i=0;i<20;i++){
            list.add("Make"+i);
        }
        return list;
    }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int point, long l) {
        Toast.makeText(this,"哈哈"+point,Toast.LENGTH_LONG).show();
    }
}


2,Xml

xml version="1.0" encoding="utf-8"?>
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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

            android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
                    android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
                            android:id="@+id/list_item"
                android:layout_width="wrap_content"
                android:layout_height="400dp">
            
                            android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ggg"/>
                            android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ggg"/>
        

    


你可能感兴趣的:(技术问题以及解决方法)