我怎么知道EditText什么时候失去焦点?

jap*_*tem 147 android lostfocus android-edittext

EditText失去焦点时我需要抓住,我已经搜索了其他问题,但我没有找到答案.

我用OnFocusChangeListener这样的

OnFocusChangeListener foco = new OnFocusChangeListener() {

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

    }
};
Run Code Online (Sandbox Code Playgroud)

但是,它对我不起作用.

ρяσ*_*я K 320

实施onFocusChangesetOnFocusChangeListener,并有一个为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
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • +1 - 但值得注意的是,如果您的编辑文本位于列表视图中,则每个按键都会导致框丢失并获得焦点.请参阅此解决方案以跟踪当前关注的框:http://stackoverflow.com/questions/9527067/android-edittext-in-listview-loses-focus-on-calling-notifydatachanged (19认同)

Cer*_*rus 8

如果您想要分解使用此接口,请使用您的Activity工具OnFocusChangeListener(),例如:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{
Run Code Online (Sandbox Code Playgroud)

在你的中OnCreate你可以添加一个监听器,例如:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);
Run Code Online (Sandbox Code Playgroud)

然后android studio会提示你从界面添加方法,接受它...就像:

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

当你有一个分解代码时,你只需要这样做:

@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:\"");
    }
}
Run Code Online (Sandbox Code Playgroud)

您编写的任何内容!hasFocus都是针对失去焦点的项目的行为,这应该是诀窍!但请注意,在这种状态下,焦点的改变可能会覆盖用户的条目!

  • 为什么不直接使用 'else' 而不是 '!hasFocus' (2认同)

Ach*_*mil 7

科特林方式

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}
Run Code Online (Sandbox Code Playgroud)