Android Значение пользовательского редактирования текста изменяется другим текстом пользовательского редактирования. - PullRequest
1 голос
/ 10 марта 2020

Intro

В одном из моих проектов я пытался создать собственный EditText с заголовком и некоторыми пользовательскими проверками. Я столкнулся со странной проблемой при тестировании этого пользовательского представления с поворотом экрана и восстановлением активности.

В чем проблема

Перед восстановлением

Когда приложение запускается, все тексты редактирования имеют правильные значения значения, которые были установлены статически из активности. Как показано на рисунке ниже:

enter image description here

После воссоздания

После поворота экрана или воссоздания действия значения EditText будут испорчены. Значения CustomEditText устанавливаются на значение последнего текста редактирования в XML. Простые (Basi c Android EditText) текстовые значения редактирования устанавливаются нормально.

enter image description here

Коды

Я скопировал коды из проект, в котором возникает эта проблема.

MainActivity

class MainActivity : AppCompatActivity() {

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

         first_custom_edit_text.header = "First header"
         first_custom_edit_text.setText("First text")

         third_custom_edit_text.header = "Third header"
         third_custom_edit_text.setText("Third text")

         first_simple_edit_text.setText("First simple - Not affected")

         second_custom_edit_text.header = "Second header"
         second_custom_edit_text.setText("Second text")

         second_simple_edit_text.setText("Second simple - Not affected")
     }
}

CustomEditText

class CustomEditText : LinearLayout {
    fun setText(value: String?){
        this.input_edit_text.text = Editable.Factory.getInstance().newEditable(value ?: "")
    }

    fun getText(): String {
        return this.input_edit_text.text.toString()
    }

    var header: String?
        get() = this.header_text_view.text.toString()
        set(value) {
            this.header_text_view.text = Editable.Factory.getInstance().newEditable(value ?: "")
        }

    constructor(context: Context) : super(context){
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs){
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        inflate(context, R.layout.ui_custom_edit_text, this)
    }
}

activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <com.example.customedittextbug.CustomEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/first_custom_edit_text"/>

    <com.example.customedittextbug.CustomEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/second_custom_edit_text"/>

    <EditText
        tools:hint="input@hint.example"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="-4dp"
        android:layout_marginRight="-4dp"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:inputType="text"
        android:id="@+id/first_simple_edit_text"/>

    <com.example.customedittextbug.CustomEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/third_custom_edit_text"/>


    <EditText
        tools:hint="input@hint.example"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="-4dp"
        android:layout_marginRight="-4dp"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:inputType="text"
        android:id="@+id/second_simple_edit_text"/>

</LinearLayout>

ui_custom_edit_text. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
            tools:text="Input header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            android:textSize="17sp"
            android:id="@+id/header_text_view"/>
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/validations_errors_holder"/>
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/common_input_holder">
        <EditText
                tools:hint="input@hint.example"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="-4dp"
                android:layout_marginRight="-4dp"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:inputType="text"
                android:id="@+id/input_edit_text"/>
        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignEnd="@+id/input_edit_text"
                android:layout_centerVertical="true"
                android:layout_marginEnd="4dp"
                android:layout_marginStart="4dp"
                android:gravity="end"
                android:orientation="horizontal"
                android:id="@+id/right_view_holder"/>
    </RelativeLayout>
</LinearLayout>

ОБНОВЛЕНИЕ

Я нашел эти два руководства с хорошим объяснением, как исправить эту проблему после ответа на мой вопрос.

Link1 , Link2

1 Ответ

1 голос
/ 10 марта 2020

Восстановление состояния выполняется по идентификатору, и все ваши пользовательские представления имеют вложенное представление с одинаковым идентификатором: input_edit_text. Таким образом, все они возвращаются в одно и то же состояние, потому что все они получили последний, сохраненный под этим идентификатором.

Этого можно избежать, установив android:saveEnabled="false" для этого EditText (хотя вы, вероятно, Вы хотите сохранить / восстановить экземпляр состояния в своем CustomEditText).

...