Как исправить поведение onClick при прокрутке RecyclerView в диалоге - PullRequest
2 голосов
/ 18 июня 2019

Я работаю над проектом, который требует Dialogs, в котором используются RecyclerViews.

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

Каждый элемент состоит из ConstraintLayout, нарисованного фона и некоторых TextViews.

Я пробовал:

  1. Использование setOnClickListener и OnClick (ButterKnife) для ConstraintLayout.
  2. Пробовал использовать их для других Views в макете.
  3. Пробовал с помощью setOnTouchListener / OnTouch (ButterKnife).
  4. Это, кажется, самый важный, я установил точку останова на слушатели, кажется, просто не сработают.
  5. Я попытался удалить изображения и цвет оттенка с onBindViewHolder в случае, если это может привести к задержке, но без успех.

Основные аспекты класса Dialog выглядят следующим образом:

public class MyDialog extends Dialog {

    @BindView(R.id.some_rv)
    RecyclerView myRV;

    @BindView(R.id.nsv)
    NestedScrollView nestedScrollView;

    public MyDialog(@NonNull Context context) {
        super(context, R.style.MyCustomisedDialogs);
        setContentView(R.layout.dialog_mydialog);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        ButterKnife.bind(this);
        setOnShowListener(d -> nestedScrollView.scrollTo(0, 0));
    }

    public void runDialog(List<MyObject> itemsList) {
        myRV.setAdapter(new MyAdapter(itemsList));
        myRV.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));

        this.show();
    }

…
}

Адаптер :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private List<MyObject> myList;

    public MyAdapter(List<MyObject> myList) {
        this.myList= myList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.my_rv_layout, viewGroup, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {

     MyObject myObject = myList.get(i);

     myViewHolder.myConstraintLayout.setOnClickListener(v -> doSomething());

     myViewHolder.headerTV.setText(myObject.getHeader());
     myViewHolder.titleTV.setText(myObject .getTitle());
     myViewHolder.mainBackgroundIV.setImageResource(myObject.getImage());
     myViewHolder.mainBackgroundIV.setColorFilter(ContextCompat.getColor(context,      myObject.getTintColor()));               

}

    @Override
    public int getItemCount() {
        return myList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

/* I have a set of BindViews for each required View
            f.i.
       ** @BindView(R.id.cl) **
       ** ConstraintLayout myConstraintLayout**
*/

        MyViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

И основные аспекты XML выглядят следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cl"
    android:layout_width="match_parent">

    <ImageView
        android:id="@+id/main_bg_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
         />

    <LinearLayout
        android:id="@+id/some_ll"
        android:layout_width="140dp"
        android:layout_height="32dp"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/my_shape"
        android:gravity="center"
        android:orientation="horizontal"
        android:visibility="gone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        >

        <TextView
            android:id="@+id/button_goto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/some_string"
            android:textColor="@color/some_custom_colour"
            android:textSize="16sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="5dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/title_tv"
        app:layout_constraintStart_toStartOf="@+id/title_tv">

        <TextView
            android:id="@+id/header_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="32sp"/>

        <ImageView
            android:visibility="gone"
            android:id="@+id/some_selection_iv"
            android:layout_width="@dimen/dp_24"
            android:layout_height="@dimen/dp_24"
            android:layout_gravity="bottom"
            android:src="@drawable/ic_some_drawable" />

    </LinearLayout>

    <TextView
        android:id="@+id/title_tv"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="12dp"
        app:layout_constraintBottom_toTopOf="@id/info_tv"
        app:layout_constraintStart_toStartOf="@id/info_tv"
        />

    <TextView
        android:id="@+id/info_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/main_bg_image"
        app:layout_constraintStart_toStartOf="@+id/main_bg_image"
        />

</android.support.constraint.ConstraintLayout>

Я ожидал бы найти способ для слушателей onClick и onTouch, по крайней мере, срабатывать, когда я касаюсь экрана после прокрутки. Даже если все элементы помещаются на главном экране RecyclerView, а прокрутка не происходит, если я нажимаю и прокручиваю, происходит то же самое поведение, означающее, что до истечения нескольких секунд ни один слушатель не активен.

...