While loading data from API, instead of using the usual loaders, we can make the loading screen
more interesting using Facebook's
Shimmer library. We can also do this shimmer effect in our Android App using
Shimmer library by Facebook.This library adds Shimmer effect on to any custom view that we define. This can be implemented in the following way:
Include the following in app-level gradle file(build.gradle)
implementation 'com.facebook.shimmer:shimmer:0.1.0'
First we have to design placeholder layout that is similar to RecyclerView's adapter layout.
placeholder.xml
Include that placeholder layout to the ShimmerLayout.
Design adapter layout for RecyclerView.
ShimmerActivity.kt
To start animation, startShimmerAnimation() can be used and for stoping it, stopShimmerAnimation() can be used.Please find below the code:
class ShimmerActivity : AppCompatActivity() {
/** Declare variables **/
private var list: MutableList = ArrayList()
lateinit var adapter: RecyclerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.shimmer_layout)
shimmerLayout.startShimmerAnimation()
Handler().postDelayed( {
shimmerLayout.stopShimmerAnimation()
shimmerLayout.visibility = View.GONE
setValues()
},5000)
}
private fun setValues() {
/** Adding values **/
list.add(User("Jeniffer Aniston"))
list.add(User("Lara Craft"))
list.add(User("Yamilet"))
list.add(User("Percy Jackson"))
list.add(User("Leo"))
list.add(User("Piper Jason"))
list.add(User("Thalia Grace"))
list.add(User("Frank"))
Log.v("list","list=="+list);
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
adapter = RecyclerAdapter(this@ShimmerActivity, list);
recyclerView.adapter = adapter
}
}
RecyclerAdapter.kt
After this,create an Adapter class for RecyclerView.
class RecyclerAdapter(val context: Context, val data: MutableList) :
RecyclerView.Adapter() {
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
if (holder != null)
holder.bindItems(data.get(position))
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val v = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return data.size
}
class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
fun bindItems(map: User) {
itemView.name.text = "Name : " + map.name
}
}
}
Finally, run the application to view the result.
