Click on an Item in recycleView and open Activity

Asked

Viewed 1,265 times

0

I’m having doubts in my application about recycleView, I would like to click on an item in the list to open an Activity with the other data in detail... Someone could help me understand how to do that. Thank you in advance

Follow the code:

Adapter

 public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

//Imageloader
private ImageLoader imageLoader;
private Context context;

List<Noticia> noticias;

//Constructor da listView
public CardAdapter(List<Noticia> noticias, Context context){
    super();

    this.noticias = noticias;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.noticia_list, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Noticia noticia =  noticias.get(position);

    //Carregando os dados
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(noticia.getImage(), ImageLoader.getImageListener(holder.imageView, R.drawable.cadeado, android.R.drawable.ic_dialog_alert));

    //Mostrando nas viws
    holder.imageView.setImageUrl(noticia.getImage(), imageLoader);
    holder.textViewNoticia.setText(noticia.getNoticia());
    holder.textViewData.setText(noticia.getData());

}

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

class ViewHolder extends RecyclerView.ViewHolder{
    //Views
    public NetworkImageView imageView;
    public TextView textViewNoticia;
    public TextView textViewData;


    //Inicializando viws
    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewNoticia);
        textViewNoticia = (TextView) itemView.findViewById(R.id.textViewNoticia);
        textViewData = (TextView) itemView.findViewById(R.id.textViewData);
    }
 }
}

Class of Volley

public class CustomVolleyRequest {

private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;

private CustomVolleyRequest(Context context) {
    this.context = context;
    this.requestQueue = getRequestQueue();

    imageLoader = new ImageLoader(requestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap>
                        cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

public static synchronized CustomVolleyRequest getInstance(Context context) {
    if (customVolleyRequest == null) {
        customVolleyRequest = new CustomVolleyRequest(context);
    }
    return customVolleyRequest;
}

public RequestQueue getRequestQueue() {
    if (requestQueue == null) {
        Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
        Network network = new BasicNetwork(new HurlStack());
        requestQueue = new RequestQueue(cache, network);
        requestQueue.start();
    }
    return requestQueue;
}

public ImageLoader getImageLoader() {
    return imageLoader;
 }
}

Call from Recycle in the application

[...]
//REcycle View
    recyclerView = (RecyclerView) findViewById(R.id.recycleView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    listNoticias = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(this);
    getData();

    //recyclerview
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        recyclerView.setOnScrollChangeListener(this);
    }


    //Iniciando o adapter
    adapter = new CardAdapter(listNoticias, this);

    // Adicionando o adapter na recycleView
    recyclerView.setAdapter(adapter);


}

private JsonArrayRequest getDataFromServer(int requestCount) {
    //Progress Bar
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    //Mostrando Progressbar
    progressBar.setVisibility(View.VISIBLE);
    setProgressBarIndeterminateVisibility(true);

    //volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Constants.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    parseData(response);
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //Se acabar os dados no servidor
                    Toast.makeText(morador.this, "Sem mais noticias", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//Vai pegar as informaçoes trazidas pelo volley
private void getData() {
    requestQueue.add(getDataFromServer(requestCount));
    //Contador incrementando
    requestCount++;
}

private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Objeto noticia
        Noticia noticia = new Noticia();
        JSONObject json = null;
        try {
            //Pegando json
            json = array.getJSONObject(i);

            //Adicionando os dados nos objetos
            noticia.setImage(json.getString(Constants.TAG_IMAGE_URL));
           noticia.setNoticia(json.getString(Constants.TAG_NOTICIA));
            noticia.setData(json.getString(Constants.TAG_DATA));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adicionando na lista
        listNoticias.add(noticia);
    }
    adapter.notifyDataSetChanged();
}

private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 1) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    if (isLastItemDisplaying(recyclerView)) {
        getData();
    }

 }
}

1 answer

1


I wear it like this:

I created an interface as a Reader:

public interface OnClickListener {
    void onItemClick(MeuObjeto meuObjeto);
}

Then, on my Adapter, I created a constructor that receives a OnClickListener. This object is where you will implement what should be done when you click on a list item.

Within the class that represents your Viewholder, I created the following method:

public void bind(final MeuObjeto meuObjeto, final OnClickListener listener) {
            itemView.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {
                    listener.onItemClick(meuObjeto);
                }
            });
        }

Finally, in the onBindViewHolder method, I called the bind method:

holder.bind(sua_lista.get(position), listener);

I hope I’ve helped you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.