Android 软键盘按键监控

最近在做项目,遇到一个比较头疼的问题,问题是需要对用户的输入进行时时监听,而大部分用户的输入是通过软键盘来完成的,而Android平台好象没有专门的对此监控事件,那该怎么办呢?

最终解决办法就是通过EditText和TextWatcher类来辅助监听。具体做法如下:

private class TextMonitor implements TextWatcher{

		 @Override
		public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {//输入前的内容
				String str_forward=s.toString().length();
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
				//正在输入的内容
				String str=s.toString().substring(start);
				
				
			tv.setText("您已经编辑的内容:"+s.toString());
			
			if(str.contains("\n")){//回车键
				
			}
				
		}

		@Override
		public void afterTextChanged(Editable s) {//输入后的内容
			String str_last=s.toString().length();
			
		}

	   }

相应控件:

private TextView tv;
private EditText edit;

tv=(TextView)findViewById(R.id.showInput);
edit=(EditText)findViewById(R.id.InputContent);
edit.addTextChangedListener(new TextMonitor());


布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/showInput"
       android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="显示您的编辑内容"
        />
   
    <EditText
         android:id="@+id/InputContent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="输入编辑内容"
          />

</LinearLayout>

目前好像还没有其他的好办法,只能这样间接监控,欢迎大家能提出更好的解决办法。

原文地址:https://www.cnblogs.com/happyxiaoyu02/p/6818974.html