2

My icons are having names icon_1, icon_2, icon_3 and so on. And I want to change the icon in the notification dynamically according to the input. The input is a number ranging from 1 to 100. if the input is 1 then icon_1 should be shown, if input is 2 then icon_2 will be shown and so on. Is it possible to set the icon in one line or we are forced to use switch case statement? The example with the code I am pasting here to better understand. Switch case statement definitely will help out but only want to know if it is possible to write in one line to save 100 lines of code.

The following lines of code may not work. But just for understanding the things, I have used. Input is a number in the variable name of num.

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification n  = new Notification.Builder(this)
    .setContentText("Subject")
    .setSmallIcon(R.drawable.icon_+"num")  //Here is the doubt..How can we modify this line to work
    .setContentIntent(pIntent)
    .setAutoCancel(true)
     .build();
NotificationManager notificationManager=NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n); 
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Rohit Singhal
  • 429
  • 1
  • 3
  • 17
  • 1
    make an integer array of your notification drawable and display it accordingly to the number you receive in notification – WISHY May 11 '15 at 06:17

1 Answers1

3

Have a look at this

//create a array of your notification icons
int[] not_icon={R.drawable.icon_1,R.drawable.icon_2,R.drawable.icon_3.......so on};

//pass the array accordingly to your input or payload
.setSmallIcon(not_icon[3]);  //3 is the number you received in your payload. 
WISHY
  • 11,067
  • 25
  • 105
  • 197
  • is there any side effects using imageResource = this.getResources().getIdentifier("icon_" + i, "drawable", getPackageName()); notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(imageResource) .setAutoCancel(false) .setOnlyAlertOnce(true) .build(); where i is variable? Thanks – user1090751 Feb 08 '20 at 18:05