onTouch无法在listview上运行

时间:2016-06-06 10:48:47

标签: android listview android-fragments ontouchlistener

创建一个我有片段的应用程序,片段的xml在下面给出

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cvCalendar"
        android:layout_below="@+id/toolbar"
        android:orientation="vertical"/>

    <ListView
        android:id="@+id/lvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Calendar"
        android:divider="#cecece"
        android:dividerHeight="2dp"
        android:background="#e4c966" />

    </RelativeLayout>

我在顶部有一个Linearlayout,用于显示日历,日历的事件显示在下面的列表中。 我想要一个功能,在向上滑动时,日历会被隐藏,在向下滑动时,它会显示日历。 java代码如下所示

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
        {
        View rootView = inflater.inflate(R.layout.layout, container, false);
        cala=(LinearLayout)rootView.findViewById(R.id.Calendar);
        rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_MOVE){

            onTouchEvent(event);
          }
        return true;
           }
        });
          return rootView;
         }
public boolean onTouchEvent(MotionEvent touchevent)
    {
       switch (touchevent.getAction())
        {
         case MotionEvent.ACTION_DOWN:
            {
                x1 = touchevent.getX();
                y1 = touchevent.getY();
                break;
              }
            case MotionEvent.ACTION_UP:
            {
                x2 = touchevent.getX();
                y2 = touchevent.getY();

                if (y1 < y2)
                {
                    Toast.makeText(getActivity(), "UP to Down Swap Performed", Toast.LENGTH_SHORT).show();
                    if ((cala.getVisibility())== View.GONE){
                       cala.setVisibility(View.VISIBLE); }
                  }

                if (y1 > y2)
                {
                    Toast.makeText(getActivity(), "Down to UP Swap Performed",Toast.LENGTH_SHORT).show();
                   if ((cala.getVisibility())== View.VISIBLE){
                       cala.setVisibility(View.GONE); }
                   }
                break;
               }
          }
       return false;
}

1 个答案:

答案 0 :(得分:0)

这对我有用: --onCreate()

lvListObject.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            onTouchEvent(motionEvent);
            return false;
        }
    });