Как я могу узнать, когда EditText теряет фокус?



мне нужно поймать, когда EditText теряет фокус, я искал другие вопросы, но я не нашел ответа.



Я OnFocusChangeListener такой



OnFocusChangeListener foco = new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub

}
};


но это не работает для меня.

441   3  

3 ответов:

реализовать onFocusChange of setOnFocusChangeListener и есть логический параметр для hasFocus. Когда это ложно, вы потеряли фокус на другой контроль.

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

ваш Activity реализовать OnFocusChangeListener() если вы хотите факторизованное использование этого интерфейса, пример:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{

в своем OnCreate вы можете добавить слушателя, например:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);

затем android studio предложит вам добавить метод из интерфейса, принять его... это будет так:

@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}

и поскольку у вас есть факторизованный код, вам просто нужно это сделать:

@Override
public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus) {
        editTextResearch.setText("");
        editTextMyWords.setText("");
        editTextPhone.setText("");
    }
    if (!hasFocus){
        editTextResearch.setText("BlaBlaBla");
        editTextMyWords.setText(" One Two Tree!");
        editTextPhone.setText("\"your phone here:\"");
    }
}

все, что Вы код в тег !hasFocus для поведения предмет, который теряет фокус, это должно сделать трюк! Но будьте осторожны, что в таком состоянии, изменение фокуса может перезаписать записи пользователя!

Его Работа Правильно

EditText et_mobile= (EditText) findViewById(R.id.edittxt);

 et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
               // code to execute when EditText loses focus
 if (et_mobile.getText().toString().trim().length() == 0) {
                        CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
                    }
            }
        }
    });



public static void showAlert(String message, Activity context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message).setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    try {
        builder.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Comments

    Ничего не найдено.