OnClickListener в ViewHolder не вводится

У меня есть представление переработчика, отображающее все сообщения, сделанные пользователем в моем приложении. Я хочу, чтобы пользователи могли щелкнуть один из постов и перейти к новому фрагменту, где они могут видеть только тот пост, который выбрали.

Когда я запускаю свой код и нажимаю на один из постов, OnCLickListener даже не запускается.

Я попытался добавить точки останова в public void OnClick, но он никогда не срабатывает. Я попытался добавить OnClick в onBindViewHolder, но понимаю, что это не очень хорошая идея.

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
public List<Post> postList;
private Context context;
private static OnItemClickListener onItemClickListener;

public PostAdapter(){
}

public interface OnItemClickListener{
    void onItemClick(View v, int position);
}

public void updateList(List<Post> list){
    postList = list;
    notifyDataSetChanged();
}

public static class PostViewHolder extends RecyclerView.ViewHolder{
    TextView postName, postUsername, postDate, postTime, postContent, postId;

    PostViewHolder(View v) {
        super(v);
        this.postName = (TextView) itemView.findViewById(R.id.name);
        this.postUsername = (TextView) itemView.findViewById(R.id.username);
        this.postDate = (TextView) itemView.findViewById(R.id.date);
        this.postTime = (TextView) itemView.findViewById(R.id.time);
        this.postContent = (TextView) itemView.findViewById(R.id.content);
        this.postId = (TextView) itemView.findViewById(R.id.postId);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = PostViewHolder.super.getAdapterPosition();
                onItemClickListener.onItemClick(v, position);
                System.out.println("doesn't even make it here");

            }
        });
    }
}

public PostAdapter(List<Post> postList, Context context){
    this.postList = postList;
    this.context = context;
}

@Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View view = LayoutInflater.from(context).inflate(R.layout.all_posts_layout, parent, false);
    return new PostAdapter.PostViewHolder(view);
}

@Override
public void onBindViewHolder(PostViewHolder holder, int position){
    Post post = postList.get(position);
    holder.postUsername.setText(String.valueOf(post.getUsername()));
    holder.postName.setText(String.valueOf(post.getName()));
    holder.postDate.setText(String.valueOf(post.getDate()));
    holder.postTime.setText(String.valueOf(post.getTime()));
}

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

Любая помощь будет очень высоко ценится!

<---card layout for each individual post---->

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="130dp"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="130dp">

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginBottom="2dp"
            android:elevation="60dp">


            <RelativeLayout
                android:id="@+id/search_term_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="1dp">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:textStyle="bold"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="italic"
                    android:layout_marginLeft="10dp"
                    android:layout_toRightOf="@id/name"
                    android:text="Username"
                    android:textSize="18sp" />

                <TextView
                    android:id="@+id/date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/content"
                    android:layout_alignParentEnd="true"
                    android:layout_marginEnd="56dp"
                    android:text="Date"
                    android:textSize="10sp" />

                <TextView
                    android:id="@+id/time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/username"
                    android:layout_toRightOf="@+id/username"
                    android:layout_alignParentEnd="true"
                    android:paddingLeft="8dp"
                    android:text="Time"
                    android:textSize="10sp" />

                <TextView
                    android:id="@+id/content"
                    android:layout_width="315dp"
                    android:layout_height="48dp"
                    android:layout_below="@+id/name"
                    android:layout_alignStart="@+id/name"
                    android:text="Content"
                    android:textSize="18sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/postId"
                    android:text="ID"
                    android:layout_below="@id/content"
                    />

            </RelativeLayout>
        </android.support.v7.widget.CardView>
        </ScrollView>
    </LinearLayout>

‹---представление переработчика для отображения всех сообщений------>


    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:tools="http://schemas.android.com/tools">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/filterBtn"
                android:text="Filter"
                android:background="@drawable/button"
                android:layout_margin="2dp"
                android:textColor="@color/common_google_signin_btn_text_dark_default"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/update_post_view"
                android:layout_width="match_parent"
                android:layout_marginTop="50dp"
                android:padding="10dp"
                android:layout_height="match_parent" />
    </RelativeLayout>

person evelcon    schedule 07.05.2019    source источник
comment
Все выглядит нормально, возможно, представление в xml является рыночным с атрибутом типа clickable=false или disabled=true или что-то в этом роде. Кроме того, в некоторых случаях событие click не может быть правильно отправлено в представление recycler, возможно, из-за неправильной конфигурации родителя recyclerview. Например, когда вид ресайклера помещается в плохо сконфигурированный CoordinatorLayout, могут возникнуть проблемы с отправкой события клика.   -  person Link182    schedule 07.05.2019
comment
Привет, спасибо за ваш ответ. Я обновил свои вопросы с помощью XML, относящегося к этому конкретному фрагменту. У меня нет таких атрибутов, как clickable=false или disabled=true. Я также пытался изменить свои макеты, чтобы увидеть, не связано ли их размещение с испорченным щелчком мыши, но мне не повезло!   -  person evelcon    schedule 07.05.2019
comment
Добавил ответ   -  person Link182    schedule 08.05.2019


Ответы (4)


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

person Link182    schedule 08.05.2019

Вам нужно установить его в onCreateViewHolder в этом представлении. Также инициируйте его в конструкторе.

person MohammadL    schedule 07.05.2019

Обновите код в соответствии с этим

public static class PostViewHolder extends RecyclerView.ViewHolder, View.OnClickListener {
    TextView postName, postUsername, postDate, postTime, postContent, postId;

    PostViewHolder(View v) {
        super(v);

        //init view
        v.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onItemClickListener.onItemClick(v, getAdapterPosition());
    }
}
person Shudipto Trafder    schedule 07.05.2019
comment
Спасибо за ответ! Я сделал это, но теперь я вижу это только в logcat, когда я нажимаю на один из элементов: D/ViewRootImpl: ViewPostImeInputStage processPointer 0 D/ViewRootImpl: ViewPostImeInputStage processPointer 1 D/ViewRootImpl: ViewPostImeInputStage processPointer 0 D/ViewRootImpl: ViewPostImeInputStage processPointer 1 - person evelcon; 07.05.2019

person    schedule
comment
Привет, я пробовал это, но получаю следующие ошибки в logcat: V/FA: неактивность, отключение от службы D/ViewRootImpl: ViewPostImeInputStage processPointer 0 D/ViewRootImpl: ViewPostImeInputStage processPointer 1 - person evelcon; 07.05.2019
comment
Вы не можете добавить ScrollView внутри макета карты. Удалите вид прокрутки из макета карты, это будет работать. - person Paras Santoki; 08.05.2019
comment
Вы не можете добавить прокрутку с помощью RecyclerView. Потому что оба имеют вертикальную прокрутку. - person Paras Santoki; 08.05.2019