We can make views more dynamic in Android by displaying real-time data in places where we can. This post will illustrate how to display today's date within a calendar icon in the bottom navigation view in Android.
1. Create an icon calendar_today_24
, in res\drawable
. For this right-click drawable, select New > Vector Asset
. Asset type
is Clip art
, and for Clip art
, select Calendar Today
icon. This will give the calendar outline icon which has no content inside it.
2. Create a menu
, bottom_menu.xml
under res\menu
with the following content. The first menu item is our calendar where we will display today's date, the day part.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_today"
android:icon="@drawable/calendar_today_24"
android:title="Today" />
...
3. Update the MainActivity
like below.
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ..
bottomNavigationView = findViewById(R.id.bottomNavigationView);
// ..
drawTodayIcon();
}
private void drawTodayIcon() {
int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
// Generate an icon with the day inside the calendar
Drawable calendarIcon = ContextCompat.getDrawable(this, R.drawable.calendar_today_24);
if (calendarIcon != null) {
Bitmap dayIcon = genCalendarIcon(calendarIcon, String.valueOf(dayOfMonth));
// Set the generated icon to the menu item
bottomNavigationView.getMenu().findItem(R.id.nav_today)
.setIcon(new BitmapDrawable(getResources(), dayIcon));
}
}
private Bitmap genCalendarIcon(Drawable baseIcon, String dayText) {
int width = baseIcon.getIntrinsicWidth();
int height = baseIcon.getIntrinsicHeight();
// Ensure valid size
if (width <= 0 || height <= 0) {
width = 100;
height = 100;
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw the base calendar icon
baseIcon.setBounds(0, 0, width, height);
baseIcon.draw(canvas);
// Prepare paint for the day number
Paint paint = new Paint();
paint.setTextSize(height / 2.5f);
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
// Calculate position to center the text
float xPos = width / 2f;
float yPos = (height / 2f) + (height / 4f);
// Draw the day number on top of the calendar icon
canvas.drawText(dayText, xPos, yPos, paint);
return bitmap;
}
}
With this we will have a nice calendar icon with date inside it which changes dynamically in the bottom navigation menu view.