Answers:
hasFocus的实现onFocusChange
,setOnFocusChangeListener
并且有一个布尔参数。如果这是错误的,则您将注意力转移到另一个控件上。
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();
}
}
使用Java 8 Lambda表达式:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});