Как изолировать представление от макета для списка onClick в представлении Android Recycler?

Я пытаюсь выбрать один элемент карты, хранящийся в представлении ресайклера, и прослушивать события щелчка и длинного щелчка. Однако, поскольку вы можете установить setOnClickListener только в представлении, мне трудно изолировать конкретный элемент (карту) от представления. В результате событие щелчка происходит по всей области макета. Пожалуйста, помогите мне изолировать одну карту от всего макета карты и помочь мне записать в нее события кликов.

ВОТ МОЙ КОД

CustomAdapter.java 

public class CardAdapterLib 
extends RecyclerView.Adapter<CardAdapterLib.LibHolder> {
private ArrayList<LibModel> libModel;
public CardAdapterLib(ArrayList<LibModel> data){
    this.libModel = data;
}
@Override
public LibHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.recycle_items,parent,false);
    // TODO: figure out how to isolate that view
//The listner I have written is getting applied to 
   the entire layout of R.layout.recycle_items
    view.setOnClickListener(LibFragment.myOnClickListener);
    return new LibHolder(view);
}
}

Мой класс фрагментов содержит представление переработчика

public class LibFragment extends Fragment {

private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;

private static ArrayList<LibModel> data;
public static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view=inflater.inflate
   (R.layout.fragment_lib_frgment,container,false);
    final CoordinatorLayout LibCoordinatorLayout =
           (CoordinatorLayout)view.findViewById(R.id.Lib_coordinatorLayout);
    myOnClickListener = new MyOnClickListener(getContext());
    recyclerView = (RecyclerView) view.findViewById(R.id.library_rv);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    data = new ArrayList<LibModel>();
    for (int i = 0; i < myData.titles.length; i++) {
        data.add(new LibModel(myData.titles[i],
    myData.authors[i],myData.lang[i],myData.id_[i]));
    }

    removedItems = new ArrayList<Integer>();
    adapter = new CardAdapterLib(data);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(getActivity(), recyclerView ,
    new RecyclerItemClickListener.OnItemClickListener() {
                @Override public void onItemClick(View view, int position)
     {Toast.makeText(getActivity(),
    "SoftPress",Toast.LENGTH_SHORT).show();
                    // Launch the Requests Fragment here
                }

         @Override
    public void onLongItemClick(View view, int position) {
    Toast.makeText(getActivity(),"Hard   Press",Toast.LENGTH_SHORT).show();
                    //Launch the Delete Fragment here
                }
            })
    );     
    return view;
}

private static class MyOnClickListener implements View.OnClickListener {
        private final Context context ;
        private MyOnClickListener(Context context) {
            this.context = context;
        }
        @Override
        public void onClick(View v) {
        // This Toast happens wherever 
        I click on the R.layout.fragment_lib_frgment area.
       // I want to make it happen only when a single card is clicked!
        Toast.makeText(context,"Clicked here DA",Toast.LENGTH_SHORT).show();
            removeItem(v);
        }
        private void removeItem(View v) {
            int selectedItemPosition = recyclerView.getChildPosition(v);
            RecyclerView.ViewHolder viewHolder
                    = recyclerView.findViewHolderForPosition
       (selectedItemPosition);
            TextView =(TextView)viewHolder.itemView.
       findViewById(R.id.title_card);
            String selectedName = (String) titleTV.getText();
            int selectedItemId = -1;
            for (int i = 0; i < myData.titles.length; i++) {
                if (selectedName.equals(myData.titles[i])) {
                    selectedItemId = myData.id_[i];
                }
            }
            removedItems.add(selectedItemId);
            data.remove(selectedItemPosition);
            adapter.notifyItemRemoved(selectedItemPosition);
       }
      }
     }

My Layout Files
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:tag="cards main container">
<android.support.v7.widget.CardView
xmlns:card_view="https://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_view"
android:layout_margin="5dp"
card_view:cardCornerRadius="10dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="6">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:layout_weight="1"
        android:id="@+id/lib_counter"
        android:textSize="120px"
        android:padding="10dp"
        android:layout_centerInParent="true"
        android:gravity="center" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="4"
        android:id="@+id/details_holder">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/title_card"
            android:layout_margin="5dp"
            android:text="Title"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/author_card"
            android:layout_margin="5dp"
            android:text="Author"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/lang_card"
            android:layout_margin="5dp"
            android:text="Language"/>
    </LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

And for the Fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/Lib_coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ch330232.pager.Activities.MainActivity">
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rvRl"
    android:layout_gravity="center_horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/library_rv"
        android:scrollbars="vertical" />

</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

person Chiraag Kashyap    schedule 02.03.2017    source источник
comment
Пожалуйста, обратитесь к приведенной ниже ссылке, которая будет работать для вас http://stackoverflow.com/questions/24471109/recyclerview-onclick   -  person vijay chhalotre    schedule 02.03.2017


Ответы (2)


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

            @Override
            public YourViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.w("Test", "Parent clicked");
                    }
                });
                return new YourViewHolder(itemView);

            }

            @Override
            public void onBindViewHolder(YourViewHolder viewHolder, int i) {

                viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.w("Test", "Checkbox clicked");
                    }
                });
            } 
person Er. Kaushik Kajavadara    schedule 02.03.2017
comment
@Chirag Пожалуйста, примите ответ, если он решил ваш запрос. Рад снова помочь. - person Er. Kaushik Kajavadara; 06.03.2017

Это происходит каждый раз, когда вы нажимаете на фрагмент, потому что вы устанавливаете его в качестве прослушивателя кликов для каждого адаптера (или представления карты), которое есть у вашего представления ресайклера. Используйте RecyclerView.addOnItemTouchListener() для активации отдельных элементов. Не добавляйте прослушиватель кликов в каждое представление внутри метода onBindView.

person Luca Nicoletti    schedule 02.03.2017