徽章类通知(kotlin):空对象引用

时间:2018-12-27 11:30:29

标签: kotlin android-actionbar badge

由于有了“徽章”,我想在ActionBar中显示一些价值。 但是,当我运行我的应用程序时,出现此错误:

overflow: hidden;

在此行上:

  

notifCount = count.findViewById(R.id.notif_count)

这是我的代码:

main.xml

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

feed_update.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

    <item
        android:id="@+id/badge"
        android:orderInCategory="100"
        android:title="@string/alertes"
        android:actionLayout="@layout/feed_update_count"
        app:showAsAction="always" />
</menu>

main_activity.kt

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/notif_count"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="32dp"
    android:minHeight="32dp"
    android:background="@drawable/red_circle"
    android:text="0"
    android:textSize="16sp"
    android:textColor="@android:color/white"
    android:gravity="center"
    android:padding="2dp"
    android:singleLine="true">
</Button>

2 个答案:

答案 0 :(得分:0)

计数应为

    val count = menu.findItem(R.id.badge)
    notifCount = count.findViewById(R.id.notif_count)
    notifCount.text = "1"

答案 1 :(得分:0)

知道了:

更改

  

android:actionLayout =“ @ layout / feed_update_count”

  

app:actionLayout =“ @ layout / feed_update_count”