In the previous article, we have already talked about how to work with RecyclerView with a simple example.
Now In this article, we will talk about how to display the description of an item in another activity on clicking of a button of each RecyclerView Item.
Get GITHUB code from here.
Updating Existing Project
1 .Firstly, we will open book_list_row.xml and add one button btn_detail to display details of each Item of recyclerView in DetailsActivity.
book_list_row.xml
<?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="wrap_content" android:layout_margin="5dp" android:orientation="horizontal"> <ImageView android:id="@+id/img_book" android:layout_width="100dp" android:layout_height="200dp"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:orientation="vertical"> <TextView android:id="@+id/book_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:text="NIRMALA" android:textColor="@color/colorPrimaryDark" android:textSize="22sp" android:textStyle="bold" /> <TextView android:id="@+id/author_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:text="Munshi Premchand" android:textStyle="bold" /> <Button android:id="@+id/btn_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" android:textColor="@android:color/white" android:layout_marginTop="6dp" android:padding="8dp" android:text="DETAIL"/> </LinearLayout> </LinearLayout>
2 .In our model class Book.java we will add a new field description and also generate setter/getter related to it.
Book.java
package com.example.lenovo.recyclerview.model; import java.io.Serializable; public class Book implements Serializable { String authorName; String bookName; int imageResource; String description; public Book(String authorName, String bookName, int imageResource,String description) { this.authorName = authorName; this.bookName = bookName; this.imageResource = imageResource; this.description = description; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getImageResource() { return imageResource; } public void setImageResource(int imageResource) { this.imageResource = imageResource; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
3 .In our BookListActivity.java while adding a Book object in a list we will pass a new fourth parameter which defines the description of an item(book_detail).
BookListActivity.java
package com.example.lenovo.recyclerview.activity; import android.os.Bundle; import com.example.lenovo.recyclerview.R; import com.example.lenovo.recyclerview.adapter.BookAdapter; import com.example.lenovo.recyclerview.model.Book; import java.util.ArrayList; import java.util.List; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class BookListActivity extends AppCompatActivity { private RecyclerView recyclerView; private List<Book> bookList = new ArrayList<Book>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_booklist); recyclerView = findViewById(R.id.recycler_view); prepareBookData(); //vertical RecyclerView recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); //provides basic animations on remove, add, and move events that happen to the items in a RecyclerView. //RecyclerView uses a DefaultItemAnimator by default. recyclerView.setItemAnimator(new DefaultItemAnimator()); // adding inbuilt divider line recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setAdapter(new BookAdapter(bookList, this)); } //preparing bookList data private void prepareBookData() { Book book = new Book("Munshi Premchand", "Nirmala", R.drawable.nirmala, "The melodramatic novel is centered on Nirmala, a young girl who was forced to marry a widower of her father's age. The plot unfolds to reveal her husband’s suspicion of a relationship between her and his eldest son, a suspicion that leads to the son’s death."); bookList.add(book); book = new Book("Harivansh Rai Bachchan", "Madhushala", R.drawable.madhushala2, "The poet tries to explain the complexity of life with his four instruments, which appear in almost every verse: madhu, madira or haala (wine), saaki (server), pyaala (cup or glass) and of course madhushala, madiralaya (pub/bar)."); bookList.add(book); book = new Book("Ramdhari Singh Dinkar", "Rashmirathi", R.drawable.rashmirathi, "Rashmirathi, which means \"charioteer of the sun”. It has a total of 4 cantos, in which all aspects of Karna's character are depicted live. In Rashmirathi, Dinkar elevated Karna from the Mahabharata story and raised him to a new land of morality and loyalty and honored him with pride. "); bookList.add(book); book = new Book("Dharamvir Bharti", "Gunahon Ka Devta", R.drawable.gunahokedevta2, "It is primarily the story of \"non expressive love and romance between two characters (Chandar and Sudha)\" showing various trappings of love in urban middle-class, pre-independence India and the emotional conflicts of enthusiastic, ambitious and idealistic youth."); bookList.add(book); book = new Book("Munshi Premchand", "Shatranj Ke Khiladi", R.drawable.shatranj2, "The two main characters are the aristocrats Mirza Sajjad Ali and Mir Raushan Ali who are deeply immersed into playing chess. Their desire for the game destroys the competency of the characters, and makes them irresponsible in their duties towards their families and society. "); bookList.add(book); book = new Book("Bhisham Sahni", "Tamas", R.drawable.tamas, "Tamas by Bhisham Sahni is a novel about the 1947 riots in Pakistan preceding the Partition of India. Based on Sahni’s first-hand experience, Tamas (Hindi for “Darkness, Ignorance”) is a fictionalized version of the riots, which pitted Muslims, Hindus and Sikhs against each other. "); bookList.add(book); book = new Book("Dharamvir Bharti", "Suraj Ka Satva Ghoda", R.drawable.suraj, "The storyteller Manek Mulla (played by Rajit Kapur) tells his friends three stories of three women he had known at different points of time in his life: Rajeshwari Sachdev (a metaphor for the middle class), Pallavi Joshi (the intellectual and affluent), and Neena Gupta (the poor)."); bookList.add(book); book = new Book("Munshi Premchand", "Karmabhumi", R.drawable.karmabhumi, "Greatly influenced by Gandhi's satyagraha movement, Karmabhumi is set in the Uttar Pradesh of the 1930s. By the beginning of the 20th century, Islam and Hinduism had coexisted in India for over a thousand years, and barring the occasional outbursts of violence, the two religious communities had lived together peacefully and shared strong social bonds except marriage."); bookList.add(book); book = new Book("Kashinath Singh", "Kassi Ka Assi", R.drawable.kashi_ka_assi, "Kashi Ka Assi by Kashinath Singh is an epic novel that brings out the life and times of Assi – a neighborhood on the southernmost ghat at Varanasi. It was the epicenter of life in Kashi – where people used to come and spend their ‘fursat’ or free time. There would be professors, student leaders, religious gurus who would consume their poison and speak their mind in a language that best describes their opinions and feelings."); bookList.add(book); book = new Book("Bhagwati Charan Verma", "Chitralekha", R.drawable.chitralekha, "Chitralekha is a slim volume of literary work that explores the very essence of the universal truths of human life in a social set up. Woven around an intense love story that reflects on and flashes out not just the various aspects of human nature but also the myriad dilemmas faced by us in our lifetime, Chitralekha - the novel and protagonist - is riveting from the first sight and word."); bookList.add(book); } }
4 .Create a new Activity DetailsActivity.java. Now corresponding to DetailActivity.java in xml file activity_detail.xml, we will add one ImageView(book_img) and three TextViews ie. book_name, book_author_name, book_detail.
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.DetailActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center"> <ImageView android:id="@+id/detail_img_book" android:layout_width="200dp" android:layout_height="200dp" android:scaleType="fitXY" android:layout_marginTop="10dp" android:background="@color/colorPrimaryDark"/> <TextView android:id="@+id/detail_book_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:text="NIRMALA" android:textColor="@color/colorPrimaryDark" android:textSize="22sp" android:layout_marginTop="10dp" android:textStyle="bold" /> <TextView android:id="@+id/detail_author_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:layout_marginTop="8dp" android:text="Munshi Premchand" android:textColor="@android:color/holo_red_dark" android:textStyle="bold" /> <TextView android:id="@+id/book_detail" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:justificationMode="inter_word" android:layout_margin="12dp" android:textStyle="italic" android:textColor="@color/colorPrimaryDark"/> </LinearLayout> </RelativeLayout>
5 .In BookAdapter.java inside onBindViewHolder method, we will add a listener on button click.
On button click, we will pass a custom object Book using intent from current activity to DetailsActivity.
We cannot pass a custom object directly from one activity to another. But to make it possible, our model class(Book.java) must implement Serializable interface.
BookAdapter.java
package com.example.lenovo.recyclerview.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.lenovo.recyclerview.R; import com.example.lenovo.recyclerview.activity.DetailsActivity; import com.example.lenovo.recyclerview.model.Book; import java.util.List; import androidx.recyclerview.widget.RecyclerView; public class BookAdapter extends RecyclerView.Adapter<BookAdapter.MyViewHolder> { private List<Book> bookList; Context context; public BookAdapter(List<Book> bookList, Context context) { this.bookList = bookList; this.context = context; } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView authorName, bookName; public ImageView imageView; Button btn_detail; public MyViewHolder(View view) { super(view); authorName = view.findViewById(R.id.author_name); bookName = view.findViewById(R.id.book_name); imageView = view.findViewById(R.id.img_book); btn_detail = view.findViewById(R.id.btn_detail); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_list_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, final int position) { holder.authorName.setText(bookList.get(position).getAuthorName()); holder.bookName.setText(bookList.get(position).getBookName()); holder.imageView.setImageResource(bookList.get(position).getImageResource()); holder.btn_detail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Book book = bookList.get(position); Intent intent = new Intent(context, DetailsActivity.class); // sending our object intent.putExtra("Book", book); context.startActivity(intent); } }); } @Override public int getItemCount() { return bookList.size(); } }
6 .Inside DetailsActivity.java we will receive the Book object which we get from Adapter class(on button click) and display its details in the UI of DetailsActivity.
DetailActivity.java
package com.example.lenovo.recyclerview.activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.lenovo.recyclerview.R;
import com.example.lenovo.recyclerview.model.Book;
import androidx.appcompat.app.AppCompatActivity;
public class DetailActivity extends AppCompatActivity {
TextView authorName, bookName, bookDetail;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Book book = (Book) getIntent().getSerializableExtra("Book");
authorName = findViewById(R.id.detail_author_name);
bookName = findViewById(R.id.detail_book_name);
bookDetail = findViewById(R.id.book_detail);
imageView = findViewById(R.id.detail_img_book);
imageView.setImageResource(book.getImageResource());
bookName.setText(book.getBookName());
authorName.setText("By " + book.getAuthorName());
bookDetail.setText(book.getDescription());
}
}
When you run the application It will look like this: