The Open Event Android project has a fragment for showing speakers of the event. Each Speaker model has image-url which is used to fetch the image from server and load in the ImageView. In some cases it is possible that image-url is null or client is not able to fetch the image from the server because of the network problem. So in these cases showing Drawable which contains First letters of the first name and the last name along with a color background gives great UI and UX. In this post I explain how to add TextDrawable as a placeholder in the ImageView using TextDrawable library.
1. Add dependency
In order to use TextDrawable in your app add following dependencies in your app module’s build.gradle file.
2. Create static TextDrawable builder
Create static method in the Application class which returns the builder object for creating TextDrawables. We are creating static method so that the method can be used all over the App.
This method first checks if the builder object is null or not and then initialize it if null. Then it returns the builder object.
3. Create and initialize TextDrawable object
Now create a TextDrawable object and initialize it using the builder object. The Builder has methods like buildRound(), buildRect() and buildRoundRect() for making drawable round, rectangle and rectangle with rounded corner respectively. Here we are using buildRect() to make the drawable rectangle.
The buildRect() method takes two arguments one is String text which will be used as a text in the drawable and second is int color which will be used as a background color of the drawable. Here ColorGenerator.MATERIAL returns material color for given string.
4. Create getNameLetters() method
The getNameLetters(String name) method should return the first letters of the first name and last name as String.
Example, if the name is “Shailesh Baldaniya” then it will return “SB”.
Here we are using split method to get the first name and last name from the name. The charAt(0) gives the first character of the string. If the name string is null then it will return “#”.
5. Use Drawable
Now after creating the TextDrawable object we need to load it as a placeholder in the ImageView for this we are using Picasso library.
Here the placeholder() method displays drawable while the image is being loaded. The error() method displays drawable when the requested image could not be loaded when the device is offline. SpeakerImage is an ImageView in which we want to load the image.
TextDrawable is a great library for generating Drawable with text. It has also support for animations, font and shapes. To know more about TextDrawable follow the links given below.
- TextDrawable: https://github.com/amulyakhare/TextDrawable
- Tutorial with list view: http://www.devexchanges.info/2015/10/listview-with-letter-in-icon-like-gmail.html