RecylerView上的OnclickListener并获取单击项目的ID

时间:2017-07-07 05:54:09

标签: android android-layout android-studio android-fragments

我需要在RecyclerView上设置onClickListener,它获取项目的Json Id Clicked并重定向到片段,该片段根据该Json ID显示产品的详细信息。我如何在适配器中实现它?我被困在这里。我能够设置onClickListener,但我无法获得Json ID。

这是我的适配器。

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

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

    private List<Ad> ads;
    private Context context;



    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);



    }

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




    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }



    }
}

这是我的MainActivity

package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);


        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());


        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });




    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}

5 个答案:

答案 0 :(得分:2)

@Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id=ads.get(position).getId();
                //You can call detail fragment here
            }
        });
    }
  

注意:从ViewHolder中删除onclick侦听器

答案 1 :(得分:1)

尝试使用以下课程,您可以获得recyclerview onclick监听器和longclick listneeers

创建 RecyclerItemClickListener

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;

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

    public void onLongItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mListener != null) {
                mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        return true;
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}


@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}

现在将lister添加到recyclerview,就像这样

        indexRecyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(MainActivity.this, indexRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {

                @Override
                public void onItemClick(View view, int position) {
                   /// perform your action here


                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            })
    );

如果有任何疑问,请询问我

答案 2 :(得分:1)

试试这个:

itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getLayoutPosition();
                    String id=ads.get(position).getId();
                    // call fragment
                }
}

在ViewHolder构造函数中添加。

答案 3 :(得分:0)

您可以在OnCkick方法中添加Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition());以检索当前对象。然后使用Interface将值传递给片段。

 @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
                Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition());
               //use interface to pass ad to the fragment....
            }

答案 4 :(得分:0)

您的适配器类应如下所示。

您必须从onClickListener课程中删除ViewHolder。并点击onBindViewHolder方法。

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

    private List<Ad> ads;
    private Context context;



    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Write your code here to send data to fragment*/
                Ad ad = ads.get(position);
            }
        });


    }

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




    public static class MyViewHolder extends RecyclerView.ViewHolder{

        ImageView thumbnail;
        TextView name, details;
        LinearLayout linearLayout;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            linearLayout=(TextView)itemView.findViewById(R.id.linearLayout); // its your main layout
        }



    }
}