简体   繁体   中英

RecyclerView and CardView implement onClick

I have a bunch of values that get pulled from mysql database and then are displayed in cardview using RecyclerView. This works great.

I want to now implement onClick on each item that is pulled, can anyone please point me in the right direction? I'm looking at being able to click on a card and have another view open with the "image", "name" and "publisher" values that are pulled from mysql using json, problem is I don't know how to pass these values onto a new activity, especially the values being pulled from mysql.

Movies.java

public class Movies extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {

//Creating a List of superheroes
private List<SuperHero> listSuperHeroes;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

//Volley Request Queue
private RequestQueue requestQueue;

//The request counter to send ?page=1, ?page=2  requests
private int requestCount = 1;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new GridLayoutManager(this,2);
    recyclerView.setLayoutManager(layoutManager);

    recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST));
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(this);

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(this);

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, this);

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
}

//Add back button to go back
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
}

public boolean onSupportNavigateUp(){
    finish();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    return true;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);

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

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigMovies.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(Movies.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(ConfigMovies.TAG_IMAGE_URL));
            superHero.setName(json.getString(ConfigMovies.TAG_NAME));
            superHero.setPublisher(json.getString(ConfigMovies.TAG_PUBLISHER));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((GridLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}
}

CardAdapter.java

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

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

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

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    //Getting the particular item from the list
    SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_blank, android.R.drawable.ic_dialog_alert));

    //Showing data on the views
    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewName.setText(superHero.getName());
    holder.textViewPublisher.setText(superHero.getPublisher());

}

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

class ViewHolder extends RecyclerView.ViewHolder{
    //Views
    public NetworkImageView imageView;
    public TextView textViewName;
    public TextView textViewPublisher;

    //Initializing Views
    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
    }
}
}

Movies.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true" />
<ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />
</LinearLayout>

superheroes_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:nestedScrollingEnabled="false"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="3dp">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/activity_horizontal_margin">
        <com.android.volley.toolbox.NetworkImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/imageViewHero"
            android:layout_gravity="center_horizontal" />
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TableRow>
                <TextView
                    android:text="Name"
                    android:paddingRight="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/textViewName"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
            </TableRow>
            <TableRow>
                <TextView
                    android:text="Publisher"
                    android:paddingRight="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/textViewPublisher"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </TableRow>
        </TableLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
  1. Let the ViewHolder class implement View.OnClickListener, then move it into CardAdapter class.
  2. Call setOnClickListener(this) just after calling super inside ViewHolder constructor like that:

     public ViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero); textViewName = (TextView) itemView.findViewById(R.id.textViewName); textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher); } @Override public void onClick(View view) { // here you can get your item by calling getAdapterPosition(); SuperHero superHero = superHeroes.get(getAdapterPosition()); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM