I have a custom view with an edittext and an imageview. I use this view multiple times in the same layout. It's behaving very strange though. Whenever I rotate the device the value from the last declared view in the xml is put into all the other views in the layout and I just can't figure out where things go wrong.
My view:
class InputView(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : ConstraintLayout(context, attrs, defStyleAttr) {
private var textInputLayout: TextInputLayout
private var textView: TextInputEditText
private var imageView: ImageView
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
init {
val view = LayoutInflater.from(context).inflate(R.layout.custom_inputview, this, true)
textInputLayout = view.custom_inputview_text_input_layout
textView = view.custom_inputview_text_input_edit_text
imageView = view.custom_inputview_image_view
attrs.let {
context.theme.obtainStyledAttributes(
it,
R.styleable.InputView,
defStyleAttr, 0).apply {
try {
textView.textSize = getDimension(R.styleable.InputView_android_textSize, 16.0f)
textView.text = SpannableStringBuilder(getString(R.styleable.InputView_android_text) ?: "")
textInputLayout.hint = getText(R.styleable.InputView_android_hint)
if (getDrawable(R.styleable.InputView_android_src) == null) {
imageView.isVisible = false
} else {
imageView.setImageDrawable(getDrawable(R.styleable.InputView_android_src))
imageView.setColorFilter(getColorOrThrow(R.styleable.InputView_android_tint))
}
textView.maxLines = getInteger(R.styleable.InputView_android_maxLines, 1)
textView.minLines = getInteger(R.styleable.InputView_android_minLines, 0)
textView.setLines(getInteger(R.styleable.InputView_android_lines, 1))
textView.inputType = getInteger(R.styleable.InputView_android_inputType, EditorInfo.IME_NULL)
textView.setCompoundDrawablesWithIntrinsicBounds(
getDrawable(R.styleable.InputView_android_drawableStart),
getDrawable(R.styleable.InputView_android_drawableTop),
getDrawable(R.styleable.InputView_android_drawableEnd),
getDrawable(R.styleable.InputView_android_drawableBottom))
} finally {
recycle()
}
}
}
}
override fun onSaveInstanceState(): Parcelable {
// 1
val bundle = Bundle()
// 2
bundle.putString("text", textView.text.toString())
// 3
Log.d("InputView", "Saving state text: ${textView.text.toString()}")
bundle.putParcelable("superState", super.onSaveInstanceState())
return bundle
}
override fun onRestoreInstanceState(state: Parcelable) {
// 4
var viewState = state
if (viewState is Bundle) {
// 5
Log.d("InputView", "Textview text: ${viewState.getString("text")}")
textView.text = SpannableStringBuilder(viewState.getString("text"))
// 6
viewState = viewState.getParcelable("superState")
}
super.onRestoreInstanceState(viewState)
}
}
I've tried overriding onSaveIntanceState() and onRestoreInstanceState(), but it doesn't change anything.
Screenshot before rotation:
Screenshot after rotation: