我是Android新手(来自iOS背景)。我创建了一个自定义/复合视图,它只是合并标语内的五个按钮:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<!--Definition for my custom segmented controller class-->
<Button
android:id="@+id/button_NA"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_NA_text"
android:background="@drawable/button_border"/>
<Button
android:id="@+id/button_1"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_1_text"
android:layout_alignStart="@id/button_NA"
android:background="@drawable/button_border"/>
<Button
android:id="@+id/button_2"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_2_text"
android:layout_toRightOf="@id/button_1"
android:background="@drawable/button_border"/>
<Button
android:id="@+id/button_3"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_3_text"
android:background="@drawable/button_border"/>
<Button
android:id="@+id/button_4"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_4_text"
android:background="@drawable/button_border"/>
<Button
android:id="@+id/button_5"
android:layout_width="35dp"
android:layout_height="35dp"
android:textSize="12sp"
android:text="@string/button_5_text"
android:background="@drawable/button_border"/>
</merge>
在继承自LinearLayout的Kotlin文件中,我实现了:
override fun onSaveInstanceState(): Parcelable? {
val bundle = Bundle()
bundle.putParcelable(STATE_SUPER_CLASS, super.onSaveInstanceState())
println("Saving segment $mSelectedSegment")
bundle.putInt(STATE_SELECTED_SEGMENT, mSelectedSegment)
return bundle
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state is Bundle) {
val bundle = state
super.onRestoreInstanceState(bundle.getParcelable(STATE_SUPER_CLASS))
val segInt = bundle.getInt(STATE_SELECTED_SEGMENT)
selectSegment(segInt)
this.id = bundle.getInt(VIEW_ID)
} else
super.onRestoreInstanceState(state)
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
// Makes sure that the state of the child views in the side
// spinner are not saved since we handle the state in the
// onSaveInstanceState.
super.dispatchFreezeSelfOnly(container)
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
// Makes sure that the state of the child views in the side
// spinner are not restored since we handle the state in the
// onSaveInstanceState.
super.dispatchThawSelfOnly(container)
}
麻烦的是,如果我动态创建并插入它,那么永远不会调用onRestoreInstanceState(),因此当屏幕方向改变时我无法恢复该值。如果我手动将此自定义视图插入到XML文件中的活动中,则会调用该函数并且它的工作方式应该如此。
我在使用View.generateViewId()创建ID后,为每个视图分配ID,因此它们都具有唯一ID。我真的很茫然,并且没有找到关于使用除this one以外的动态添加视图来保存状态的示例,但是它说为了使这项工作我需要手动重新分配视图他们以前持有的ID。
我不确定如何在不保存每个动态创建的视图,其状态和ID的情况下完成该操作,然后在onCreate中再次手动构建它们...在这种情况下onRestoreInstanceState中的要点是什么( )。