公司正在开发的app有需求是:在编辑栏中弹出自定义的键盘,并且正常显示光标。刚开始以为很简单,按照网上的教程,没一个完美实现的。所以自己琢磨了下再结合其他人的代码,自己实现了需求。
1.首先禁用系统自带键盘,并关联自定义的键盘:
利用Edittext 的setOnTouchListener 方法,设置控件被点击时响应的键盘:
getcashmoneyedit.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(ShopGetInComeCashActivity.this.findViewById(R.id.keyboard).getVisibility()==View.GONE)
{
ShopGetInComeCashActivity.this.findViewById(R.id.keyboard).setVisibility(View.VISIBLE);
}
return true;
}
});
此方法设置后,点击edittext 控件的时候不会再启动系统键盘,会弹出你定义好的键盘。上面的方法中每次点击时间都会隐藏或者显示我定义好的键盘。
2.光标的显示:
禁用系统键盘后想显示光标可以用一下方法
public void disableShowSoftInput() {
Class<EditText> cls = EditText.class;
Method method;
try {
method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(getcashmoneyedit, false);
} catch (Exception e) {
}
try {
method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(getcashmoneyedit, false);
} catch (Exception e) {
}
}
该方法用反射的方式 调用Edittext 中的setShowSoftInputOnFocus和setSoftInputShownOnFocus方法,都设置为false。如果感兴趣可以看源码。
3.此时光标可以闪烁了,但是还不能随着边框的文字移动,再调用Edittext的addTextChangedListener 方法即可:
getcashmoneyedit.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) {
getcashmoneyedit.setSelection(s.length());
}
});
在afterTextChanged 方法中监听输入文字的长度,并动态设置光标位置。
测试手机:魅蓝note2,华为荣耀
以下是效果图: