1. EditText通过代码聚焦和失焦
// _editText.setFocusable(true);//设置输入框可聚集 _editText.setFocusableInTouchMode(true);//设置触摸聚焦 _editText.requestFocus(); //聚焦 _editText.clearFocus(); //失焦
2. EditText输入框改变监听
//输入框文本改变的回调 _editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { Toast.makeText(EditTextActivity.this, "text change before", Toast.LENGTH_SHORT).show(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Toast.makeText(EditTextActivity.this, "text changing", Toast.LENGTH_SHORT).show(); } @Override public void afterTextChanged(Editable s) { // 每次改变,会回调此方法 Toast.makeText(EditTextActivity.this, "text change after:" + s, Toast.LENGTH_SHORT).show(); } });
注意:EditText每次改变,会调用 afterTextChanged 方法
3. 完整代码
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:gravity="left" android:orientation="vertical" android:padding="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Text模式:" /> <EditText android:id="@+id/edit_text_text" android:layout_width="300dp" android:layout_height="40dp" android:background="@drawable/edit_background" android:hint="text" android:inputType="text" android:padding="5dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/button_edit_focus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="聚焦" /> <Button android:id="@+id/button_edit_blur" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:padding="10dp" android:text="失焦" /> </LinearLayout> </LinearLayout>