【问题标题】:Android Kotlin Starting Activity From Utils Class Results In SavedInstanceState Being NullAndroid Kotlin 从 Utils 类启动 Activity 导致 SavedInstanceState 为 Null
【发布时间】:2020-01-31 05:51:37
【问题描述】:

为了事先澄清,我已经在 SO 中广泛搜索了类似的问题,以找到我问题的答案。

我将参考以下内容(仅举几例):

我有一个 MainActivity 和其他四个不同的活动,我们称它们为 A 到 D。

我还有一个 Utilities 类,它将点击侦听器设置为在活动 A 到 D 中找到的图像按钮。

这些监听器然后打开一个新的活动,E。

由于某种原因,在活动 E 的 onCreate 方法中,savedInstanceState 始终为空。 我尝试从 MainActivity 设置监听器,但无济于事。 我还从 MainActivity 传递了上下文(而不是使用滚动视图),但这也没有效果

下面是代码的sn-p。

Utilities.kt

class Utilities {

companion object {
    /...

    fun setTooltipsAndListeners(scrollView: ScrollView) {
        val buttons: ArrayList<View> = scrollView.touchables
        for (button in buttons) {
            val tooltipText = button.contentDescription
            if (tooltipText != null) {
                TooltipCompat.setTooltipText(button, tooltipText)
            }

            button.setOnClickListener(object : View.OnClickListener {
                override fun onClick(v: View?) {

                    val tag: String? = v?.tag as? String
                    val intent = Intent(scrollView.context, ActivityE::class.java)
                    intent.putExtra("symbol_name", tooltipText)
                    intent.putExtra("symbol_image", tag)

                    scrollView.context.startActivity(intent)

                }
            })

        }
    }

   /...
}

ActivityE.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.layout_name)
    setDataToUI(savedInstanceState)
}

private fun setDataToUI(savedInstanceState: Bundle?) {

    if (savedInstanceState == null) {
        Log.d("TAG", "savedInstanceState IS NULL")
        return
    }

  /... Inner logic that is not relevant
}

【问题讨论】:

    标签: android kotlin android-intent android-activity


    【解决方案1】:

    您需要使用getIntent() 而不是savedInstanceState。所以你的代码会变成这样:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_name)
        setDataToUI(intent)
    }
    
    private fun setDataToUI(intent: Intent?) {
    
        if (intent.getStringExtra("symbol_name") == null) {
            Log.d("TAG", "No data passed for symbol_name")
            return
        }
        // Do the same for other strings. Or alternatively, you can pass Bundle 
        // data from your Utility and retrieve the bundle through the intent as well
    }
    

    savedInstanceState 用于在活动状态更改时存储数据,但您正在通过实用程序类中的 Intent 传递数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-13
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多