MenuItem中使用app:actionLayout(Switch)造成空指針異常

使用情況:

MenuItem中使用了app:actionLayout

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.nfcdemo.MainActivity">

    <item
        android:id="@+id/action_open_close_nfc"
        android:orderInCategory="100"
        android:title=""
        app:actionLayout="@layout/menu_switch"
        app:showAsAction="always" /> 
</menu>

menu_switch對應的布局中包含了一個Switch控件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   >
    <Switch
       android:id="@+id/switchForActionBar"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:text=""
       android:checked="false"
       android:theme="@style/ThemeOverlay.SwitchBar"
       />

</RelativeLayout>

錯誤原因

直接使用錯誤方式(findViewById)獲取Switch,導致獲取失敗,使用時空指針異常

解決辦法

使用正確的方式(menu-->menuitem-->actionview-->switch)獲取Switch

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem switchItem = menu.findItem(R.id.action_open_close_nfc);
   mSwitch = (Switch) switchItem.getActionView().findViewById(R.id.switchForActionBar);
    if (mNfcAdapter != null) {
        mSwitch.setChecked(mNfcAdapter.isEnabled());
    }
    return true;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容