这是我参与 8 月更文挑战的第 22 天,活动详情查看: 8月更文挑战
背景
在Android中EditText是最常用的基础控件之一, 作为输入框, 承接着项目中绝大部分的信息录入功能, 同时需求也是五花八门.本篇文章就简单介绍一下EditText控件的基本功能
基本功能
获取焦点
edit.requestFocus();
获取焦点同时弹出键盘
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
清空焦点
edit.clearFocus();
清空焦点同时隐藏键盘
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
强制获取焦点
使用这种组合,在某些机型中可以直接弹出软键盘
edit.setFocusable(true);
edit.requestFocus();
edit.setFocusableInTouchMode(true);
设置光标位置
动态设置光标位置
edit.setSelection(10);
设置图片
edit.setCompoundDrawables(left,top, right,bottom);
监听文字变化
edit.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
beforeTextChanged为文字修改前的回调,onTextChanged为文字修改中的回调,afterTextChanged为文字修改后的回调
注意 需要特别注意的是, 如果在以上回调中要修改控件中的文字, 一定要特别注意不要陷入死循环.即:文字改变->watcher接收到通知->setText->文字改变->watcher接受到通知->..
控件获取焦点的回调
edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
hasFocus值为true时代表控件获取了焦点,为false是代表控件失去了焦点
监听软键盘按下键的回调
edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
return false;
}
});
一般会判断
actionId == EditorInfo.IME_ACTION_DONE软件盘中的Done键或者send键或者搜索键
屏蔽复制粘贴功能
创建一个类实现ActionMode.Callback接口中的所有方法
public class ActionModeCallbackInterceptor implements ActionMode.Callback {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
}
在需要的地方进行调用
edit.setCustomInsertionActionModeCallback( new ActionModeCallbackInterceptor());