从 Notification Shade 更改主题时的非空参数

Non-null parameter when changing theme from Notification Shade

每当我使用 Notification Shade 在设备深色和浅色主题之间切换时,(运行 时我的应用程序)似乎总是由于某种原因崩溃。我的应用程序的最小 API 是 29 (Android 10)。 logcat 指向错误原因不明显的代码行。 (import android.view.*)。我怎样才能防止这种情况再次发生?

 java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter view

Activity class

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (savedInstanceState == null) supportFragmentManager.beginTransaction()
            .replace(R.id.detail_container, MainFragment())
            .commitNow()
    }
}

主要片段class

package com.example.vp2

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.app.NavUtils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import java.util.*

class MainFragment : androidx.fragment.app.Fragment() {
    private lateinit var mySpinnerItems: Array<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val v = inflater.inflate(R.layout.fragment_main, container, false)
        super.onCreate(savedInstanceState)

        return v
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        val mSpinner = requireView().findViewById<Spinner>(R.id.mSpinner)
        val mViewPager2 = requireView().findViewById<ViewPager2>(R.id.mViewPager2)

        // Spinner items array
        mySpinnerItems = arrayOf(
            "Item 1",
            "Item 2",
            "Item 3",
        )

        val arrayAdapter = ArrayAdapter(requireView().context, android.R.layout.simple_spinner_item, mySpinnerItems)
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item)
   
        mSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                when {
                    mySpinnerItems[position] == "Item 1" -> {
                        mViewPager2.setCurrentItem(0, false)
                    }

                    mySpinnerItems[position] == "Item 2" -> {
                        mViewPager2.setCurrentItem(1, false)
                    }

                    else -> {
                        mViewPager2.setCurrentItem(2, false)
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                mViewPager2.setCurrentItem(0, false)
            }
        }
        mSpinner.adapter = arrayAdapter

        mViewPager2.adapter = MySpinnerFragmentAdapter(this)
        mViewPager2.orientation = ViewPager2.ORIENTATION_HORIZONTAL

        mViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        mSpinner.setSelection(0)
                    }
                    1 -> {
                        mSpinner.setSelection(1)
                    }
                    else -> {
                        mSpinner.setSelection(2)
                    }
                }
                super.onPageSelected(position)
            }
        })

        super.onActivityCreated(savedInstanceState)
    }

    private class MySpinnerFragmentAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
        private val intItems = 3

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> Fragment1()
                1 -> Fragment2()
                else -> Fragment3()
            }
        }

        override fun getItemCount(): Int {
            return intItems
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        menu.clear()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return if (item.itemId == android.R.id.home) {
            val intent = activity?.let { NavUtils.getParentActivityIntent(it) }
            when {
                intent != null -> {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                    NavUtils.navigateUpTo(requireActivity(), intent)
                }
            }
            true
        } else super.onOptionsItemSelected(item)
    }
}

主要activity布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/detail_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
</LinearLayout>

主要片段布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/detail_container">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/mViewPager2"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />

    <!-- divider (start)-->
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:background="?android:attr/textColorSecondary" />
    <!-- divider (end)-->

    <Spinner
        android:id="@+id/mSpinner"
        style="@style/Widget.AppCompat.Spinner.Underlined"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"/>
</LinearLayout>

更新

cactustictacs 的建议

    mSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            when {
                mySpinnerItems[position] == "Item 1" -> {
                    mViewPager2.setCurrentItem(0, false)
                }

                mySpinnerItems[position] == "Item 2" -> {
                    mViewPager2.setCurrentItem(1, false)
                }

                else -> {
                    mViewPager2.setCurrentItem(2, false)
                }
            }
        }

        override fun onNothingSelected(parent: AdapterView<*>) {
            // Code to perform some action when nothing is selected
            mViewPager2.setCurrentItem(0, false)
        }
    }

堆栈跟踪(请 post 将来的实际文本而不是屏幕截图!)说一些名为 view 的参数在其类型指定为非空时为空(View 而不是 View?)。这是由 AdapterView.onItemSelected 运行 引起的(因此它是该方法中的 view 参数),它在 onActivityCreated

中声明

基本上 onItemSelected 方法的前两个参数 AdapterView<*>?View?.

需要具有可空类型

如果让 IDE 自动实现方法(使用 ctrl+I),这就是你得到的结果 - the docs 具有 View! 类型,这意味着因为它来自 Java,它可能为空,也可能不是,不知道 - 所以安全的默认值是 View?。当您指定非空类型(如 View)时,Kotlin 会进行空检查以确保 - 这就是 Intrinsics.checkNotNullParameter 调用的内容。你得到了一个 null,所以它抛出了一个异常!

是的,让它们可以为空,然后在访问它们之前对它们进行空检查。还要确保 appcompat 是最新的(至少 1.2.0),因为当您 used setDefaultNightMode

时,他们遇到了 Activity 没有被重新创建的问题