[RecyclerView and Glide] implements an Android e-book reading APP, gliderecyclerview

Source: Internet
Author: User

[RecyclerView and Glide] implements an Android e-book reading APP, gliderecyclerview

Http://www.cnblogs.com/xfangs/

You are welcome to comment at the bottom of this article. You must encourage your support !!!

This series of tutorials is only for learning and communication.

For the final effect of the novel reader, see the first blog

 

 

Preface

In the previous article, we implemented the basic functions of ViewPager. According to the plan, we need to use ViewPager to insert two pages of views to make our e-book reading app. One is used to display the current shelf, one class is used to display different categories. In this section, we will implement the classification option on the page marked as find.

Involved components or frameworks: RecyclerView, Glide

 

 

First, Layout

Similarly, here, the small party can only briefly introduce the basic usage of RecyclerView because of its limited level, and cannot do anything if it involves more profound operations.

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:orientation="vertical" android:layout_width="match_parent" 4     android:layout_height="match_parent"> 5  6     <android.support.v7.widget.RecyclerView 7         android:id="@+id/recyler_view_find_book" 8         android:layout_margin="8dp" 9         android:layout_width="match_parent"10         android:layout_height="match_parent"/>11 12 </LinearLayout>

There are no complex steps. We only need to add the RecyclerView to one of the two la s of the previous ViewPager to complete the entire list layout.

Of course, you may encounter some accidents.

This indicates that the RecyclerView library has not been introduced. On the Design page, locate the RecyclerView from the components on the left and click. The Selection box is displayed.

After adding the database, we can see that the RecyclerView is correctly displayed on the interface.

 

 

Adapter

The main battlefield we work on this time is the Fragment mentioned in the previous section, which is one of the two pages of ViewPager.

Review the code.

 1     public static class FindBooksFragment extends Fragment { 2  3         public FindBooksFragment() { 4         } 5  6         @Override 7         public View onCreateView(final LayoutInflater inflater, ViewGroup container, 8                                  Bundle savedInstanceState) { 9 10             View rootView = inflater.inflate(R.layout.pager_book_find, container, false);11 12             return rootView;13         }14 15     }

As mentioned earlier, ViewPager will callOnCreateViewThis function, so we will initialize it here.

Before that, we need to complete the RecyclerView Adapter. Similarly, the adapter serves to combine data and pages. Specifically, assume that a project in the list can be divided into three types. We design a layout for these three types of elements, and then pass the data of each item to the adapter. The adapter can select the corresponding layout based on the data, then, each item is displayed.

First, create a class.

 

The RecyclerView adapter has already been described by many blogs on the Internet. If you want to find an article about the past, let's take a general look.

... Search Time...

 

After understanding it, we know that we need to write a layout for the list items, which is also mentioned above.

Create a layout File

 

Book_find_item.xml

 1 <?xml version="1.0" encoding="utf-8"?> 2 <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" 3     xmlns:tools="http://schemas.android.com/tools" 4     android:id="@+id/bookFind_cardview" 5     android:layout_width="match_parent" 6     android:layout_height="wrap_content" 7     android:layout_margin="4dp" 8     android:foreground="?android:attr/selectableItemBackground" 9     android:clickable="true">10 11     <ImageView12         android:id="@+id/bookFind_image"13         android:layout_width="match_parent"14         android:layout_height="150dp"15         android:scaleType="centerCrop"16         tools:src="@color/cardview_dark_background"/>17 18     <TextView19         android:id="@+id/bookFind_class"20         android:layout_width="match_parent"21         android:layout_height="match_parent"22         android:background="#00000000"23         android:textColor="#FFFFFF"24         android:textStyle="normal|bold"25         android:textSize="14sp"26         android:gravity="center"27         tools:text="123"/>28 29 </android.support.v7.widget.CardView>

 

Here, we use a new component, CardView, which reflects the latest Android design style, just-right corner, realistic shadow, click special effects, and so on, multiple Attributes are available for adjustment.

In particular, the bold font in the above Code, a new namespaceTools,Before using it, we should first declare it on the outermost part.

 

Android studio will automatically complete the first few letters.

 

The tools namespace provides the test results. The attributes with the name "" are ignored during the program running and only used for test preview, making development more convenient. Is the effect we get during the preview,

 

When the program runs, will it still look like it?

(No)

 

After creating the layout file, we can start to write the adapter.

 

First, create an interface to obtain click events.

 1     private OnItemClickListener listener; 2  3     public void setOnItemClickListener(OnItemClickListener listener) { 4         this.listener = listener; 5     } 6  7     public interface OnItemClickListener { 8         void onItemClick(View view, int position); 9         void onItemLongClick(View view, int position);10     }

 

Create a new class in the adapter class.

 1     static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { 2         View tocView; 3         private TextView textview_bookFindClass; 4         private ImageView imageView; 5         private OnItemClickListener listener; 6  7         public ViewHolder(View itemView, OnItemClickListener l) { 8             super(itemView); 9             tocView = itemView;10             textview_bookFindClass = (TextView) itemView.findViewById(R.id.bookFind_class);11             imageView = (ImageView) itemView.findViewById(R.id.bookFind_image);12             listener = l;13             itemView.setOnClickListener(this);14             itemView.setOnLongClickListener(this);15         }16 17 18         @Override19         public void onClick(View v) {20             if (listener != null) {21                 listener.onItemClick(v, getAdapterPosition());22             }23         }24 25         @Override26         public boolean onLongClick(View v) {27             if (listener != null) {28                 listener.onItemLongClick(v, getAdapterPosition());29             }30             return false;31         }32     }

 

 

It may be a little complicated. The function of this class is to cache the list items. It is not clear about the lower-level items. If you search for items online, you will not learn to sell them now, you are welcome to join us in the discussion.

The ViewHolder class inherits from RecyclerView. ViewHolder. To achieve click listening, two interfaces are also added: one is the click interface and the other is the long-pressed interface.

Starting from the constructor's 1.1 Point Understanding, constructor receives two parameters, one is the View of each item, and the other is the click listener of each item. After the component is initialized, set the listener and send the View and position to the listener Based on the interface settings.

If it is not clear, copy the code first. If it is used more often, you will naturally understand it.

 

Then, complete its constructor in the AdapterBookFind class, which is set as needed. here we need to pass the category name to the adapter and display it on each item, therefore, a string list is transmitted. You can also transmit the data you want to transmit as needed.

1     private ArrayList<String> myCategory;2 3     public AdapterBookFind(ArrayList<String> category) {4         this.myCategory = category;5     }

 

Next, we need to rewrite a function to obtain a ViewHolder instance.

 

1     private Context context;2     @Override3     public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {4         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_find_item, parent, false);5         context = parent.getContext();6         final ViewHolder holder = new ViewHolder(view, listener);7 8         return holder;9     }

Here, we declare a variable called context and initialize the variable.

 

1     @Override2     public int getItemCount() {3         return myCategory.size();4     }

Like the ViewPager adapter, we also need to rewrite the number function and return a value based on the data.

 

Now, we will set different content for each item in the list.

 

 1     @Override 2     public void onBindViewHolder(final ViewHolder holder, int position) { 3         holder.textview_bookFindClass.setText(myCategory.get(position)); 4  5         switch (position) { 6             case 0: 7                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView); 8                 break; 9             case 1:10                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);11                 break;12             case 2:13                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);14                 break;15             case 3:16                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);17                 break;18             case 4:19                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);20                 break;21             case 5:22                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);23                 break;24             case 6:25                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);26                 break;27             case 7:28                 Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);29                 break;30             default:31 32                 break;33         }34         holder.imageView.setColorFilter(Color.parseColor("#55555555"));35 36     }

 

Because there are only two components in our layout file that reflect the data content, TextView and ImageView.

The third line is to select different strings based on different locations for setting, with no difficulty.

 

Before talking about the switch, let's look at the last line.

holder.imageView.setColorFilter(Color.parseColor("#55555555"));

Set the color filter for the imageView, because I want to display a white text on the image, so that the image can be dimmed properly to highlight the text.

 

Switch can also be understood, but there is a strange thingGlide.

Actually, it is not difficult to understand that the role of this switch is to select different files for display based on different locations. Of course, we can use the built-in ImageView method to set images, however, ImageView can only set image resources locally or in the APK. There is no way to set network images or many unsupported image types (such as GIF). Besides, when the local images are large, choppy occurs inevitably.

At this time, Glide appears. It can quickly load various images and automatically compress the images based on the display size. The same statement can load and cache network images if an image link is input.

 

Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imageView);

 

As shown in the code above, an image in the APK resource can be loaded. Here we only have one icon file, so the icon file is passed to the imageView.

 

However, if you just copy and paste the code to your project, your program will report an error, indicating that the Glide is not found. This is because Glide is not officially provided, we need to introduce it manually.

 

Find the file above.

 

Add the last row and select synchronization.

In this way, we introduce Glide.

Integration

1 public static class FindBooksFragment extends Fragment {2 3 public FindBooksFragment () {4} 5 6 private RecyclerView recyclerView; 7 private StaggeredGridLayoutManager preview; 8 private AdapterBookFind bookAdapterBookFind; 9 10 @ Override11 public View onCreateView (final LayoutInflater inflater, ViewGroup container, 12 Bundle savedInstanceState) {13 14 final ArrayList <String> bookClass = new ArrayList <> (); 15 bookClass. add ("// xuanhuan"); 16 bookClass. add ("// martial arts"); 17 bookClass. add ("// City"); 18 bookClass. add ("// history"); 19 bookClass. add ("// game"); 20 bookClass. add ("// sci-fi"); 21 bookClass. add ("// "); 22 bookClass. add ("// All"); 23 24 View rootView = inflater. inflate (R. layout. pager_book_find, container, false); 25 recyclerView = (RecyclerView) rootView. findViewById (R. id. recyler_view_find_book); 26 27 staggeredGridLayoutManager = new StaggeredGridLayoutManager (2, StaggeredGridLayoutManager. VERTICAL); 28 recyclerView. setLayoutManager (staggeredGridLayoutManager); 29 bookAdapterBookFind = new AdapterBookFind (bookClass); 30 recyclerView. setAdapter (bookAdapterBookFind); 31 32 bookAdapterBookFind. setOnItemClickListener (new AdapterBookFind. onItemClickListener () {33 @ Override34 public void onItemClick (View view, int position) {35Log. e (TAG, "onItemClick: 111 ");36} 37 38 @ Override39 public void onItemLongClick (View view, int position) {40Log. e (TAG, "onItemLongClick: 222 ");41} 42}); 43 44 return rootView; 45} 46 47Private static final String TAG = "FindBooksFragment ";48 49}

 

First, initialize our string list. StaggeredGridLayoutManager is the layout manager of our list. Android provides three layout managers for different list effects, multi-row lists, waterfall stream lists, and different sliding directions, you can use another Baidu layout manager.

Therefore, in line 27-30, we set the List Manager and adapter for RecyclerView, starting from line 32, and set the click listener for the adapter. We do not set the function for the moment, use the log tool to output it to Android Monitor (the log statement has a shortcut key ).

 

 

Effect

Run the program and you will see

 

 

We have completed a new section. Now we can try to replace different images and try to use network images (do not forget to add network access permissions ).

To be continued... use in the next articleLitePal complete bookshelvesComing soon !!!

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.