176

フォーカスを失ったときにキャッチする必要がありEditTextます。他の質問を検索しましたが、答えが見つかりませんでした。

私はOnFocusChangeListenerこのように使用しました

OnFocusChangeListener foco = new OnFocusChangeListener() {

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

    }
};

しかし、それは私にはうまくいきません。

4

5 に答える 5

377

hasFocusonFocusChangesetOnFocusChangeListenerブールパラメータを実装します。これがfalseの場合、別のコントロールへのフォーカスを失っています。

 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
            }
        }
    });
于 2012-05-16T21:49:18.977 に答える
9

このインターフェースを因数分解して使用したい場合は、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){
    doSomethingWith(editTextResearch.getText(),
      editTextMyWords.getText(),
      editTextPhone.getText());
  }
}

それでうまくいくはずです!

于 2016-06-15T09:36:38.727 に答える
7

Kotlinの方法

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}
于 2019-03-05T09:51:55.413 に答える
1

その適切な動作

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();
    }

}
于 2017-10-30T12:40:10.327 に答える
1

Java 8ラムダ式の使用:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );
    }        
});
于 2019-03-29T12:46:16.613 に答える