android 监听edittext 焦点,android EditText 的聚焦和失焦,输入框的监听

packagecom.example.myapplication;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.text.Editable;importandroid.text.TextWatcher;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.Toast;importcom.example.administrator.myapplication.R;public class EditTextActivity extendsAppCompatActivity {privateEditText _editText;

@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.activity_edit_text);

_editText=findViewById(R.id.edit_text_text);//获取焦点和失去焦点

_editText.setFocusable(true);

_editText.setFocusableInTouchMode(true);

Button button_focus=findViewById(R.id.button_edit_focus);

button_focus.setOnClickListener(newEditTextListener());

Button button_blur=findViewById(R.id.button_edit_blur);

button_blur.setOnClickListener(newEditTextListener());//聚焦和失焦的回调

_editText.setOnFocusChangeListener(newView.OnFocusChangeListener() {

@Overridepublic void onFocusChange(View v, booleanhasFocus) {if(hasFocus) {

Toast.makeText(EditTextActivity.this, "text focus", Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(EditTextActivity.this, "text blur", Toast.LENGTH_SHORT).show();

}

}

});//输入框文本改变的回调

_editText.addTextChangedListener(newTextWatcher() {

@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, intafter) {

Toast.makeText(EditTextActivity.this, "text change before", Toast.LENGTH_SHORT).show();

}

@Overridepublic void onTextChanged(CharSequence s, int start, int before, intcount) {

Toast.makeText(EditTextActivity.this, "text changing", Toast.LENGTH_SHORT).show();

}

@Overridepublic voidafterTextChanged(Editable s) {//每次改变,会回调此方法

Toast.makeText(EditTextActivity.this, "text change after:" +s, Toast.LENGTH_SHORT).show();

}

});

}class EditTextListener implementsView.OnClickListener{

@Overridepublic voidonClick(View view) {switch(view.getId()) {caseR.id.button_edit_focus :

_editText.requestFocus();//聚焦

break;caseR.id.button_edit_blur:

_editText.clearFocus();//失焦

break;

}

}

}

}

你可能感兴趣的:(android,监听edittext,焦点)