自定义视图,不调用onSaveInstanceState

时间:2018-05-27 19:12:00

标签: android kotlin android-view android-custom-view

我创建了一个自定义视图,并尝试在屏幕旋转时自动恢复状态(就像EditText自动恢复当前输入文本一样),但是当我看到日志时,onSaveInstanceState未被调用,并且仅调用onRestoreInstanceState。有什么问题?

class MyView:LinearLayout
{
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context, attrs, defStyleAttr)

    init
    {
        isSaveEnabled=true
    }

    override fun onSaveInstanceState(): Parcelable
    {
        return super.onSaveInstanceState()
        Log.d("ss", "save")
    }

    override fun onRestoreInstanceState(state: Parcelable?)
    {
        super.onRestoreInstanceState(state)
        Log.d("ss", "restore")
    }
}

活动布局:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.loser.mylayouttest.MyView
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</AbsoluteLayout>

的活动:

class MainActivity : AppCompatActivity()
{

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

1 个答案:

答案 0 :(得分:1)

您无法看到Log.d("ss", "save")被调用的原因仅仅是在return语句之后调用代码行。实际上调用onSaveInstanceState()。要查看日志移动Log.d("ss", "save") return super.onSaveInstanceState()以上。