Rumah > Java > javaTutorial > teks badan

Bagaimana untuk Mencegah Gelung Infinite Apabila Mengosongkan Medan EditText dalam Android?

DDD
Lepaskan: 2024-11-14 12:45:02
asal
641 orang telah melayarinya

How to Prevent an Infinite Loop When Clearing EditText Fields in Android?

Android EditText: Listening for Text Changes and Emptying Other Field

To ensure that only one of two fields contains data, it becomes imperative to clear the other field if one is modified. This need arises in situations where field1 and field2, two EditText fields, should not both hold values simultaneously.

As presented in the question, attaching a TextWatcher to both field1 and field2 causes an infinite loop where the fields clear each other indefinitely.

Solution:

To resolve this issue, implement a check to only clear the opposing field when the current field contains text. This can be achieved by examining the length of the input string.

In the modified code below, an "if" statement checks whether the length of the input string (i.e., the text entered into the current field) is different than 0. If so, the opposing field is cleared:

field1.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start,
        int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start,
        int before, int count) {
        if(s.length() != 0)
            field2.setText("");
    }
});

field2.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start,
        int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start,
        int before, int count) {
        if(s.length() != 0)
            field1.setText("");
    }
});
Salin selepas log masuk

By incorporating this check, the infinite loop is broken, and the desired functionality is achieved, ensuring that only one of the fields ever contains data at any given time.

Atas ialah kandungan terperinci Bagaimana untuk Mencegah Gelung Infinite Apabila Mengosongkan Medan EditText dalam Android?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan