RecyclerView 的 OnItemClickListener [重复]

Posted

技术标签:

【中文标题】RecyclerView 的 OnItemClickListener [重复]【英文标题】:OnItemClickListener for a RecyclerView [duplicate] 【发布时间】:2018-01-24 10:41:53 【问题描述】:

我想在我的RecyclerView 中添加项目点击监听器,这样当我点击某个项目时,它会启动一个新的Intent 并从网络服务器检索有关该项目的数据。我尝试了很多建议,但都没有帮助。

我的 RecylerView 类

public class GetPrice extends AppCompatActivity 
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private  CustomAdapter adapter;
private List<MyData> dataList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getpricerecycle);
    recyclerView =(RecyclerView) findViewById(R.id.recycler_view);

    dataList = new ArrayList<>();
    load_data_from_server(0);
    gridLayoutManager = new GridLayoutManager(this,1);
    recyclerView.setLayoutManager(gridLayoutManager);
    adapter = new CustomAdapter(this,dataList);
    recyclerView.setAdapter(adapter);



private void load_data_from_server(final int id) 
    AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() 
        @Override
        protected Void doInBackground(Integer... params) 
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("http://172.20.10.7/anfal/getPrice.php?id="+id).build();
            try 
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());
                for(int i=0;i<array.length();i++ )
                    JSONObject jsonobject = array.getJSONObject(i);
                    MyData data=new MyData(jsonobject.getInt("id"),jsonobject.getString("name"),jsonobject.getString("price"),jsonobject.getString("image"));
                    dataList.add(data);
                
             catch (IOException e) 
                e.printStackTrace();
             catch (JSONException e) 
                System.out.println("End Of Content");
            


            return null;
        

        @Override
        protected void onPostExecute(Void aVoid) 
            adapter.notifyDataSetChanged();
        
    ;
task.execute(id);


这是我用于回收站视图的 coustm 适配器

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>                                                                  
        private Context context;
        private List<MyData> my_data;
        public CustomAdapter(Context context, List<MyData> my_data) 
        this.context = context;
        this.my_data = my_data;
    

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.getpricecardview,parent,false);
        return new ViewHolder(itemView);

    
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) 
           holder.name.setText(my_data.get(position).getName());
           holder.price.setText(my_data.get(position).getPrice());


    @Override
    public int getItemCount() 
        return my_data.size();
    

    public static class ViewHolder extends RecyclerView.ViewHolder 
        public TextView name;
        public TextView price;
        public ImageView imageview;
        public ViewHolder(View itemView) 
            super(itemView);
            name=(TextView)itemView.findViewById(R.id.description);
            price=(TextView) itemView.findViewById(R.id.nameofp);
            imageview=(ImageView) itemView.findViewById(R.id.imgevie);
        
    


【问题讨论】:

试试这个答案***.com/questions/28296708/… ***.com/a/35970486/1563038 【参考方案1】:

实现recyclerview的item点击最简单的方法是在适配器的onBindViewHolder方法中实现。

@Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) 
       vh.itemView.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                //use position value  to get clicked data from list
            
        );
    

【讨论】:

【参考方案2】:

在您的RecyclerView.Adapter 中简单地创建一个您可以使用的界面。

private onItemClickListener mItemClickListener;

public void setOnItemClickListener(onItemClickListener mItemClickListener) 
        this.mItemClickListener = mItemClickListener;


public interface onItemClickListener 
    void onItemClickListener(View view, int position, MyData myData);

在这种情况下,mItemClickListener 是适配器内部的一个全局变量,这两个方法也在适配器内部。

然后在您的ViewHolder 中,使用itemView.setOnClickListener(this)(或您希望单击以检索数据的任何组件)对您的itemView 应用点击侦听器

@Override
public void onClick(View view) 
    if (mItemClickListener != null) 
        mItemClickListener.onItemClickListener(view, getAdapterPosition(), my_data.get(getAdapterPosition()));
    

然后,这将传递已单击的视图、所述视图的位置以及该位置内列表中包含的对象。

因此,在您的Activity 中,您只需调用interface

adapter.setOnItemClickListener(new CustomAdapter.onItemItemClickListener() 
    @Override
    public void onItemClickListener(View view, int position, MyData data) 
    //do on item click functionality here
    
);

【讨论】:

【参考方案3】:

第一种方法

recyclerViewObject.addOnItemTouchListener(
        new RecyclerItemClickListener(
            getContext(),
            recyclerViewObject,
            new RecyclerItemClickListener.OnItemClickListener() 
                @Override public void onItemClick(View view, int position) 
                    // view is the clicked view (the one you wanted
                    // position is its position in the adapter
                
                @Override public void onLongItemClick(View view, int position) 
                
            
        )
    );

第二种方式

public interface PositionClickListener 
    void itemClicked(int position); 

在适配器中

public class MyRecyclerAdapter extends RecyclerView.Adapter

    public final PositionClickListener listener;

    public MyRecyclerAdapter(PositionClickListener listener)
    
         this.listener = listener;
    

    private void createView(int position)
    
        View v = new View();
        v.setOnClickListener(new OnClickListener()
            listener.itemClicked(position);
        );
    

Reference

【讨论】:

【参考方案4】:

实际上,使用 recyclerView 和 OnClickListener 的最佳做法是这样做:

在你的活动中:

//Add this line in the onCreate method
//Add more parameters if needed for your adapter
DataAdapter myDataAdapter = new DataAdapter (context, myClickListener);


private View.OnClickListener myClickListener = new View.OnClickListener()

    @Override
    public void onClick(View view)
    
        int position = view.getTag()
        //Do something...
    
;

在你的适配器中

private View.OnClickListener myClickListener;
private Context context;

 public DataAdapter (Context context, View.OnClickListener myClickListener)

    this.context = context;
    this.myClickListener = myClickListener;


public class ViewHolder extends RecyclerView.ViewHolder 


    //Your attributes

    public myViewHolder(View v, View.OnClickListener myClickListener) 
    
        super(v);
        v.setOnClickListener(myClickListener);
    


@Override
public void onBindViewHolder(myViewHolder holder, int position)

    holder.itemView.setTag(position)

当然,它适用于任何类型的 clickListener。

希望有帮助!!

【讨论】:

【参考方案5】:

你可以改变 ViewHolder

         public ViewHolder(View itemView) 
            super(itemView);

            name=(TextView)itemView.findViewById(R.id.description);
            price=(TextView) itemView.findViewById(R.id.nameofp);
            imageview=(ImageView) itemView.findViewById(R.id.imgevie);



            itemView.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 

                // Here is the action


                
            );


        

【讨论】:

【参考方案6】:

在 CustomAdapter.ViewHolder 中的 itemView 中添加点击事件

即itemView.setOnClickListener() 和里面的 onClick() 方法获取点击项的位置是这样的:

getAdapterPosition()

【讨论】:

以上是关于RecyclerView 的 OnItemClickListener [重复]的主要内容,如果未能解决你的问题,请参考以下文章

recyclerview 内的 RecyclerView 只显示父 recyclerview 的最后一项

关于RecyclerView

RecyclerView详解

RecyclerView

RecyclerView小结

水平 RecyclerView 内的水平 RecyclerView