[英]How can I know when an EditText loses focus?
当EditText
失去焦点时,我需要抓住,我搜索了其他问题,但没有找到答案。
我像这样使用OnFocusChangeListener
OnFocusChangeListener foco = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
}
};
但是,它对我不起作用。
实现onFocusChange
的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) {
// todo: get your previous values to compare the new ones
// They should exclude "" or get back to previous state...
if (hasFocus) {
editTextResearch.setText("");
editTextMyWords.setText("");
editTextPhone.setText("");
}
// in case it loses focus, do a better job getting back
// the previous value if no changes where made there:
if (!hasFocus){
editTextResearch.setText("BlaBlaBla");
editTextMyWords.setText(" One Two Tree!");
editTextPhone.setText("\"your phone here:\"");
}
}
您在!hasFocus
编写的任何代码都是针对失去焦点的项目的行为,这应该可以解决问题! 但请注意,在这种状态下,焦点的变化可能会覆盖用户的条目!
科特林方式
editText.setOnFocusChangeListener { _, hasFocus ->
if (!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();
}
}
使用 Java 8 lambda 表达式:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.