根据@Fletcher Johns 的回答,我想出了:
- 自定义布局
- 可以从 XML 膨胀
- 能够保存/恢复直接和间接的孩子。我改进了@Fletcher Johns 的答案,将 ID 保存在 String->Id 映射而不是 IntArray 中。
- 唯一的小缺点是您必须事先声明可保存的子视图。
open class AddressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
protected lateinit var countryInputLayout: TextInputLayout
protected lateinit var countryAutoCompleteTextView: CountryAutoCompleteTextView
protected lateinit var cityInputLayout: TextInputLayout
protected lateinit var cityEditText: CityEditText
protected lateinit var postCodeInputLayout: TextInputLayout
protected lateinit var postCodeEditText: PostCodeEditText
protected lateinit var streetInputLayout: TextInputLayout
protected lateinit var streetEditText: StreetEditText
init {
initView()
}
private fun initView() {
val view = inflate(context, R.layout.view_address, this)
orientation = VERTICAL
countryInputLayout = view.findViewById(R.id.countryInputLayout)
countryAutoCompleteTextView = view.findViewById(R.id.countryAutoCompleteTextView)
streetInputLayout = view.findViewById(R.id.streetInputLayout)
streetEditText = view.findViewById(R.id.streetEditText)
cityInputLayout = view.findViewById(R.id.cityInputLayout)
cityEditText = view.findViewById(R.id.cityEditText)
postCodeInputLayout = view.findViewById(R.id.postCodeInputLayout)
postCodeEditText = view.findViewById(R.id.postCodeEditText)
}
// Declare your direct and indirect child views that need to be saved
private val childrenToSave get() = mapOf<String, View>(
"coutryIL" to countryInputLayout,
"countryACTV" to countryAutoCompleteTextView,
"streetIL" to streetInputLayout,
"streetET" to streetEditText,
"cityIL" to cityInputLayout,
"cityET" to cityEditText,
"postCodeIL" to postCodeInputLayout,
"postCodeET" to postCodeEditText,
)
private var viewIds: HashMap<String, Int>? = null
override fun onSaveInstanceState(): Parcelable? {
// Create a bundle to put super parcelable in
val bundle = Bundle()
bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState())
// Store viewIds in the bundle - initialize if necessary.
if (viewIds == null) {
childrenToSave.values.forEach { view -> view.id = generateViewId() }
viewIds = HashMap<String, Int>(childrenToSave.mapValues { (key, view) -> view.id })
}
bundle.putSerializable(STATE_VIEW_IDS, viewIds)
return bundle
}
override fun onRestoreInstanceState(state: Parcelable?) {
// We know state is a Bundle:
val bundle = state as Bundle
// Get mViewIds out of the bundle
viewIds = bundle.getSerializable(STATE_VIEW_IDS) as HashMap<String, Int>
// For each id, assign to the view of same index
if (viewIds != null) {
viewIds!!.forEach { (key, id) -> childrenToSave[key]!!.id = id }
}
super.onRestoreInstanceState(bundle.getParcelable(SUPER_INSTANCE_STATE))
}
companion object {
private const val SUPER_INSTANCE_STATE = "saved_instance_state_parcelable"
private const val STATE_VIEW_IDS = "state_view_ids"
}
}