In this tutorial, i would explain how you can load a recyclerview with the first item selected (background color changed) and also make the background of the other items changed when clicked.
Follow the step by step process.
[Highlighted selected item in recycler view screenshot][1]
[1]: https://i.stack.imgur.com/hHP0W.png
You can see full steps of RecyclerView Highlighted items
Start by creating a new Android Studio project. Go to File -> New Project.
Open your color file `(res -> values -> colors.xml)`. Paste the below code.
colors.xml
> <resources>
> <color name="colorPrimaryLight">#07C4AF</color>
> <color name="colorPrimary">#035F56</color>
> <color name="colorPrimaryDark">#00574B</color>
> <color name="colorAccent">#D81B60</color>
>
> </resources>
**create a new android resource layout. Right click on your project file, select New -> Android Resource Layout . give it the name “recycler_items”.**
**recycler_items.xml**
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cardview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:contentPaddingLeft="18dp"
card_view:contentPaddingRight="18dp"
card_view:cardCornerRadius="15dp"
card_view:cardElevation="7dp"
card_view:cardBackgroundColor="@color/colorPrimary"
android:layout_marginLeft="8dp"
>
<TextView
android:id="@+id/tv_pets"
android:layout_gravity="center"
android:textSize="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pet Name"
android:textColor="#fff"/>
</android.support.v7.widget.CardView>
**Right click on your project file, select New -> Java Class. Give it the name “RecyclerAdapter“. This is the adapter that would be used to populate our recyclerview.**
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private List<Pets> petsList;
private Context context;
private static int lastClickedPosition = -1;
private int selectedItem;
public RecyclerAdapter(Context context, List<Pets> petsList) {
this.context = context;
this.petsList = petsList;
selectedItem = 0;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_items, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.itemView.setTag(petsList.get(position));
holder.name.setText(petsList.get(position).getName());
holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorPrimaryLight));
if (selectedItem == position) {
holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorPrimaryDark));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int previousItem = selectedItem;
selectedItem = position;
notifyItemChanged(previousItem);
notifyItemChanged(position);
}
});
}
@Override
public int getItemCount() {
return petsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.tv_pets);
cardView = (CardView) view.findViewById(R.id.cardview);
}
}
}
> Lets create our model class that holds information about the pets
Pets.java
package androidnoon.recyclerview.select;
public class Pets {
private int id;
private String Name;
private String Description;
public Pets(int id, String name, String description) {
this.id = id;
Name = name;
Description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".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>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="@+id/RvPets"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
**MainActivity.java**
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView RvPets;
List<Pets> petsList = new ArrayList<>();
RecyclerAdapter recyclerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerAdapter = new RecyclerAdapter(MainActivity.this, petsList);
RvPets = (RecyclerView) findViewById(R.id.RvPets);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
RvPets.setLayoutManager(linearLayoutManager);
RvPets.setAdapter(recyclerAdapter);
preparePetsData();
}
private void preparePetsData() {
Pets pet = new Pets(1, "Cat", "Cute, has 4 legs");
petsList.add(pet);
pet = new Pets(2, "Bird", "Can Fly, has 2 legs");
petsList.add(pet);
pet = new Pets(3, "Dog", "Cute, has 4 legs");
petsList.add(pet);
pet = new Pets(4, "Fish", "has no leg");
petsList.add(pet);
pet = new Pets(5, "Hamster", "Cute, has 4 legs");
petsList.add(pet);
recyclerAdapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}