使用变量代替R.drawable

时间:2014-02-06 13:01:00

标签: java android

我的申请表中有通知。 但是在不同的活动中,我会在通知栏中显示不同的图标。 而我只是想知道如何在语法上写这个。

Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.card_red)
                .setWhen(System.currentTimeMillis()).setTicker(message)
                .setContentTitle("Real Madrid 2:1 Barcelona")
                .setContentText(message).setContentIntent(pIntent)
                .getNotification(); 

我有一个持有事件类型的变量 - event = 5; if(event == 5)icon = card_red; 我必须将该图标变量放入通知创建者。

3 个答案:

答案 0 :(得分:2)

private int[] icons = new int[] {R.drawable.card_red,  R.drawable.card_blue,  R.drawable.card_black};    

您应该正确地将图标的索引映射到数组中。

Notification notification = new Notification.Builder(this)
                .setSmallIcon(icons[event])
                .setWhen(System.currentTimeMillis()).setTicker(message)
                .setContentTitle("Real Madrid 2:1 Barcelona")
                .setContentText(message).setContentIntent(pIntent)
                .getNotification(); 

答案 1 :(得分:2)

这里有一个简单的开关盒有什么问题?对事件类型变量switch,并返回相应的drawable ID。然后将该ID传递到setSmallIcon

int drawable = -1;
switch(eventType) {
  case 5 : drawable = R.drawable.card_red; break;
  case 6 : drawable = R.drawable.card_blue; break;
  //Other cases as appropriate
}

答案 2 :(得分:1)

int drawableId = -1
switch(eventId) {
 case EVENT0:
    drawableId = R.drawable.event0;
    break;
 case EVENT1:
    drawableId = R.drawable.event1;
    break;
 case EVENT2:
    drawableId = R.drawable.event2;
    break;
}
if (drawableId != -1) {
Notification notification = new Notification.Builder(this)
                .setSmallIcon(drawableId)
                .setWhen(System.currentTimeMillis()).setTicker(message)
                .setContentTitle("Real Madrid 2:1 Barcelona")
                .setContentText(message).setContentIntent(pIntent)
                .getNotification(); 
}