RecyclerView is one of those views that you wouldn’t believe haven’t been in android for a long time. It’s so popular and heavily used since it’s introduction in API level 22.
RecyclerView class resides in android.view.ViewGroup. Android describes it as a flexible view for providing a limited window into a large dataset. Well for us, we are interested in this dataset: how to sort it.
Sorting data is important especially in components like recyclerview wihich can display massive amounts of data. No user would like the problem of having to read through each of the list of items just to find a specific data. he can simply sort and reach it quicker.
===
This example uses Collections API to sort data in ascending and descending order.User clicks sort button to toggle between sorting ascending and descending. You can find more details about WebView here.
Screenshot
- Here’s the screenshot of the project.
Android RecyclerView Sort Example
Common Questions this example explores
- How to sort data in RecyclerView.
- Sorting Collections in android java.
- RecyclerView with CardViews. Sort CardViews
- Sort RecyclerView in ascending and descending manner.
Tools Used
This example was written with the following tools:
- OS: Windows 8.1
- IDE : AndroidStudio
- Emulator : Genymotion
- Language : Java
Libaries Used
- No third party library was used in this project.
Source Code
Lets jump directly to the source code.
Build.Gradle
- Normally in android projects, there are two build.gradle files. One is the app level build.gradle, the other is project level build.gradle. The app level belongs inside the app folder and its where we normally add our dependencies and specify the compile and target sdks.
- Also Add dependencies for AppCompat and Design support libraries.
- Our MainActivity shall derive from AppCompatActivity while we shall also use Floating action button from design support libraries.
apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "26.0.0" defaultConfig { applicationId "com.tutorials.hp.recyclerviewsort" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7' compile 'com.android.support:design:26.+' compile 'com.android.support:cardview-v7:26.+' }
MyViewHolder.java
- Our ViewHolder class.
- Derives from RecyclerView.ViewHolder.
- Holds our view for Recycling.
package com.tutorials.hp.recyclerviewsort; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; public class MyViewHolder extends RecyclerView.ViewHolder { TextView nameTxt; public MyViewHolder(View itemView) { super(itemView); nameTxt = (TextView) itemView.findViewById(R.id.nameTxt); } }
MyAdapter.java
- Our Adapter class.
- Derives from RecyclerView.ViewHolder.
- Inflates our model layout into RecyclerView ViewItems.
- Adapts our data to RecyclerView ViewItems.
package com.tutorials.hp.recyclerviewsort; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> { Context c; ArrayList<String> spacecrafts; public MyAdapter(Context c, ArrayList<String> spacecrafts) { this.c = c; this.spacecrafts = spacecrafts; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(c).inflate(R.layout.model, parent, false); return new MyViewHolder(v); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { //BIND DATA holder.nameTxt.setText(spacecrafts.get(position)); } @Override public int getItemCount() { return spacecrafts.size(); } }
MainActivity.java
- Launcher activity.
- Derives from AppCompatActivity.
- ActivityMain.xml inflated as the contentview for this activity.
- We initialize views and widgets inside this activity.
- We fill an arraylist,sort it, pass it to our adapter and set that adapter to our RecyclerView.
package com.tutorials.hp.recyclerviewsort; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.Collections; public class MainActivity extends AppCompatActivity { RecyclerView rv; Button sortBtn; MyAdapter adapter; // String[] spacecrafts={"Juno","Hubble","Casini","WMAP","Spitzer","Pioneer","Columbia","Challenger","Apollo","Curiosity"}; //DATA private static ArrayList<String> spacecrafts =new ArrayList<>(); private boolean ascending = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.initializeViews(); this.fillSpacecrafts(); } //INITIALIZE VIEWS private void initializeViews() { rv = (RecyclerView) findViewById(R.id.rv); rv.setLayoutManager(new LinearLayoutManager(this)); sortBtn = (Button) findViewById(R.id.sortBtn); sortBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sortData(ascending); ascending = !ascending; } }); } /* * SORT */ private void sortData(boolean asc) { //SORT ARRAY ASCENDING AND DESCENDING if (asc) { Collections.sort(spacecrafts); } else { Collections.reverse(spacecrafts); } //ADAPTER adapter = new MyAdapter(this, spacecrafts); rv.setAdapter(adapter); } /* FILL SPACECRAFTS DATA */ private void fillSpacecrafts() { spacecrafts.clear(); spacecrafts.add("Kepler"); spacecrafts.add("Casini"); spacecrafts.add("Voyager"); spacecrafts.add("New Horizon"); spacecrafts.add("James Web"); spacecrafts.add("Apollo 15"); spacecrafts.add("WMAP"); spacecrafts.add("Enterprise"); spacecrafts.add("Spitzer"); spacecrafts.add("Galileo"); spacecrafts.add("Challenger"); spacecrafts.add("Atlantis"); spacecrafts.add("Apollo 19"); spacecrafts.add("Huygens"); spacecrafts.add("Hubble"); spacecrafts.add("Juno"); spacecrafts.add("Aries"); spacecrafts.add("Columbia"); //ADAPTER adapter = new MyAdapter(this, spacecrafts); rv.setAdapter(adapter); } }
ActivityMain.xml
- Template layout.
- Contains our ContentMain.xml.
- Also defines the appbarlayout, toolbar as well as floatingaction buttton.
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout android_layout_width="match_parent" android_layout_height="match_parent" tools_context="com.tutorials.hp.recyclerviewsort.MainActivity"> <android.support.design.widget.AppBarLayout android_layout_width="match_parent" android_layout_height="wrap_content" android_theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android_id="@+id/toolbar" android_layout_width="match_parent" android_layout_height="?attr/actionBarSize" android_background="?attr/colorPrimary" app_popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android_id="@+id/fab" android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_gravity="bottom|end" android_layout_margin="@dimen/fab_margin" app_srcCompat="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout>
ContentMain.xml
- Content Layout.
- Defines the views and widgets to be displayed inside the MainActivity.
- In this case its a simple webview.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout android_layout_width="match_parent" android_layout_height="match_parent" app_layout_behavior="@string/appbar_scrolling_view_behavior" tools_context="com.tutorials.hp.recyclerviewsort.MainActivity" tools_showIn="@layout/activity_main"> <LinearLayout android_orientation="vertical" android_layout_width="match_parent" android_layout_height="match_parent"> <Button android_text="Sort" android_layout_centerInParent="true" android_layout_width="match_parent" android_layout_height="70dp" android_background="@color/colorAccent" android_padding="10dp" android_id="@+id/sortBtn" android_layout_marginRight="5.0dp" /> <android.support.v7.widget.RecyclerView android_id="@+id/rv" android_layout_width="match_parent" android_layout_height="wrap_content" /> </LinearLayout> </android.support.constraint.ConstraintLayout>
Model.xml
- ViewItem Layout.
- Root layout is CardView.
- Defines the views and widgets to be inflated as our viewitems.
- In this case its a cardview with textview.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView android_orientation="horizontal" android_layout_width="match_parent" android_layout_margin="10dp" card_view_cardCornerRadius="5dp" card_view_cardElevation="5dp" android_layout_height="200dp"> <TextView android_layout_width="match_parent" android_layout_height="wrap_content" android_textAppearance="?android:attr/textAppearanceLarge" android_text="Name" android_id="@+id/nameTxt" android_padding="10dp" android_textColor="@color/colorAccent" android_textStyle="bold" android_layout_alignParentLeft="true" /> </android.support.v7.widget.CardView>
Video/Preview
- Video version of this tutorial. Coming soon…
Download
- Download the Project below:
How To Run
- Download the project above.
- You’ll get a zipped file,extract it.
- Open the Android Studio.
- Now close, already open project.
- From the Menu bar click on File >New> Import Project.
- Now Choose a Destination Folder, from where you want to import project.
- Choose an Android Project.
- Now Click on “OK“.
- Done, your done importing the project,now edit it.
Conclusion.
We saw a simple android webview example. How to load webpages from online via url, from assets folder and from string data.
More
YouTube
- Visit our channel for more examples like these.
- Lets share tips and ideas in our Facebook Page.
Oclemy,Cheers.