android - 我怎么知道EditText什么时候失去焦点?
我需要抓住当OnFocusChangeListener失去焦点时,我已经搜索了其他问题,但我没有找到答案。
我用过这个OnFocusChangeListener
OnFocusChangeListener foco = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
}
};
但是,它对我不起作用。
3个解决方案
296 votes
实现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
}
}
});
ρяσѕρєя K answered 2019-06-09T10:11:31Z
8 votes
如果您想要分解使用此接口,请将您的!hasFocus实施为OnFocusChangeListener(),例:
public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{
在!hasFocus中,您可以添加一个侦听器,例如:
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中编码的任何内容都是针对丢失焦点的项目的行为,这应该可以解决问题! 但请注意,在这种状态下,焦点的改变可能会覆盖用户的条目!
Cerberus answered 2019-06-09T10:12:30Z
0 votes
它的工作正常
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();
}
}
Keshav Gera answered 2019-06-09T10:12:57Z