Swipe для Recycle View не работает должным образом - PullRequest
0 голосов
/ 26 марта 2020

Я хотел бы реализовать смахивание для моего вида корзины в целом (не для отдельной строки элемента). Я пытался использовать жест смахивания, пользовательский класс прослушивания на ощупь, но все же он не работал гладко. временами он работает нормально, но в большинстве случаев он проводит пальцами слева направо, даже если я проведу пальцем справа налево. ниже мой собственный код класса. и я реализовал это для представления recycle в моем классе фрагмента. извините, что я не могу опубликовать весь свой код, поскольку я не должен был это делать. Кто-нибудь может мне помочь, пожалуйста. ?

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class RelativeLayoutTouchListener implements View.OnTouchListener {
    static final String logTag = "ActivitySwipeDetector";
    public Context activity;
    static final int MIN_DISTANCE = 100;// TODO change this runtime based on screen resolution. for 1920x1080 is to small the 100 distance
    private float downX, downY, upX, upY;
    MaterialCalendarView calendarView;
    String slectedDate;
    Calendar calendar;
    ICalendarEventList list_interf_obcj;
    // ISwipeFragment iSwipeFragment;

    public RelativeLayoutTouchListener(Context mainActivity, MaterialCalendarView calendarViewes, String slectedDatesnew, Calendar calendares, ICalendarEventList list_interf_obcj, ISwipeFragment iSwipeFragment) {
        this.activity = mainActivity;
        this.slectedDate = slectedDatesnew;
        this.calendarView = calendarViewes;
        this.calendar = calendares;
        this.list_interf_obcj = list_interf_obcj;
        //this.iSwipeFragment = iSwipeFragment;
    }

    public void setDate(String slectedDatesnew) {
        this.slectedDate = slectedDatesnew;
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                return true;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();

                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // swipe horizontal?
                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        //   v.scrollBy(5,5);
                        // setDate(NewCalendarFragment.selectedDate);

                        onLeftToRightSwipe();
                        return true;
                    }
                    if (deltaX > 0) {
                        //   v.scrollBy(5,5);
                        //  setDate(NewCalendarFragment.selectedDate);
                        onRightToLeftSwipe();
                        return true;
                    }
                } else {
                    Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long horizontally, need at least " + MIN_DISTANCE);
                    // return false; // We don't consume the event
                }

                // swipe vertical?
                if (Math.abs(deltaY) > MIN_DISTANCE) {
                    // top or down
                    if (deltaY < 0) {
                        this.onTopToBottomSwipe();
                        return true;
                    }
                    if (deltaY > 0) {
                        this.onBottomToTopSwipe();
                        return true;
                    }
                } else {
                    Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long vertically, need at least " + MIN_DISTANCE);
                    // return false; // We don't consume the event
                }

                return false; // no swipe horizontally and no swipe vertically
            }// case MotionEvent.ACTION_UP:
        }
        return false;
    }

    public void onRightToLeftSwipe() {
        Log.i(logTag, "RightToLeftSwipe!");
        leftToRightAction(calendar, calendarView, activity, list_interf_obcj, slectedDate);
    }


    public void onLeftToRightSwipe() {
        Log.i(logTag, "LeftToRightSwipe!");
        rightToLeftAction(calendar, calendarView, activity, list_interf_obcj, slectedDate);
    }

    public void onTopToBottomSwipe() {
        Log.i(logTag, "onTopToBottomSwipe!");
    }

    public void onBottomToTopSwipe() {
        Log.i(logTag, "onBottomToTopSwipe!");
    }


    private void rightToLeftAction(Calendar calendarold, MaterialCalendarView calendarView, Context mainActivity, ICalendarEventList list_interf_obcj, String selectedDates) {
        Calendar calendar = Calendar.getInstance();
            SimpleDateFormat parser = null;
        try {
            parser = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
            calendar.setTime(parser.parse(selectedDates));
        } catch (ParseException e) {
            e.printStackTrace();
        }


        calendar.add(Calendar.DATE, 1);
           Log.i(logTag, "RightSwipe!--> " + calendar.getTime().toString());
        calendarView.setDateSelected(calendar.getTime(), true);
        calendarView.setSelectedDate(calendar.getTime());
        Log.i(logTag, "RightSwipe!--> " + calendar.getTime().toString());
        SimpleDateFormat formated = new SimpleDateFormat("MM/dd/yyyy");
        String onDateSelected_format = formated.format(calendar.getTime()).toString();
        setDate(parser.format(calendar.getTime()));
        calendarView.setFocusable(true);
        calendarView.setCurrentDate(calendar);

        new CalendarEventListTask(mainActivity, JsonUtil.CalendarListAPiJsonFormat(mainActivity, SessionStores.getSchoolId(mainActivity).toString(), onDateSelected_format, ""), Constants.CAl_LIST_TAG, list_interf_obcj, onDateSelected_format);

    }

    private void leftToRightAction(Calendar calendarold, MaterialCalendarView calendarView, Context mainActivity, ICalendarEventList list_interf_obcj, String selectedDates) {
        Calendar calendar = Calendar.getInstance();
           SimpleDateFormat parser = null;
        try {
            parser = new SimpleDateFormat("MM/dd/yyyy", Locale.US);

            calendar.setTime(parser.parse(selectedDates));
        } catch (ParseException e) {
            e.printStackTrace();
        }


        calendar.add(Calendar.DATE, -1);

        Log.i(logTag, "LeftSwipe!--> " + calendar.getTime().toString());

        calendarView.setDateSelected(calendar.getTime(), true);

        calendarView.setSelectedDate(calendar.getTime());
        SimpleDateFormat formated = new SimpleDateFormat("MM/dd/yyyy");
        String onDateSelected_format = formated.format(calendar.getTime()).toString();
        setDate(parser.format(calendar.getTime()));
               calendarView.setFocusable(true);
        calendarView.setCurrentDate(calendar);


        new CalendarEventListTask(mainActivity, JsonUtil.CalendarListAPiJsonFormat(mainActivity, SessionStores.getSchoolId(mainActivity).toString(), onDateSelected_format, ""), Constants.CAl_LIST_TAG, list_interf_obcj, onDateSelected_format);     

    }

}``` 

1 Ответ

0 голосов
/ 26 марта 2020

Прежде всего, вы можете использовать новый жест навигации, проверьте эту ссылку:

https://developer.android.com/training/gestures/gesturenav

с другой стороны, почему бы вам не поставить свой recyclerView внутри viewPager, он будет обрабатывать пролистывание, и ваше представление будет смахивать в хорошем состоянии

вы можете поместить recyclerView внутри представления или внутри фрагмента, и вы можете использовать этот рабочий процесс, чтобы делать то, что вы хотите

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...