Android禁止Edittext弹出软键盘并且使光标正常显示

公司正在开发的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,华为荣耀

以下是效果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值