控件EditText的setOnEditorActionListener方法的使用

说明:需要注意的是 setOnEditorActionListener这个方法,并不是在我们点击EditText的时候触发,也不是在我们对EditText进行编辑时触发,而是在我们编辑完之后点击软键盘上的各种键才会触发。

因为通过布局文件中的imeOptions可以控制软件盘右下角的按钮显示为不同按钮。所以和EditorInfo搭配起来可以实现各种软键盘的功能。

各种属性对应:

  • imeOptions=”actionUnspecified” –> EditorInfo.IME_ACTION_UNSPECIFIED
  • imeOptions=”actionNone” –> EditorInfo.IME_ACTION_NONE
  • imeOptions=”actionGo” –> EditorInfo.IME_ACTION_GO
  • imeOptions=”actionSearch” –> EditorInfo.IME_ACTION_SEARCH
  • imeOptions=”actionSend” –> EditorInfo.IME_ACTION_SEND
  • imeOptions=”actionNext” –> EditorInfo.IME_ACTION_NEXT
  • imeOptions=”actionDone” –> EditorInfo.IME_ACTION_DONE

用法

  • 布局中定义一个EditText控件
 <EditText
        android:id="@+id/ET_phonenumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/buttonAdd"
        android:hint="@string/enter_new_note" 
        android:imeOptions="actionDone"             // 这里和onEditorAction中actionId对应。
        android:inputType="text"/>
  • 定义一个可编辑的editText控件
EditText ET_phone = (EditText) findViewById(R.id.ET_phonenumber);
  • 添加setOnEditorActionListener方法
ET_phone.setOnEditorActionListener(new OnEditorActionListener() {  
            @Override  
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
               if (actionId == EditorInfo.IME_ACTION_DONE) {   // 按下完成按钮,这里和上面imeOptions对应
                text.setText("Editing EditorInfo.IME_ACTION_DONE");  
                return false;   //返回true,保留软键盘。false,隐藏软键盘
                }
            }  
        });  

猜你喜欢

转载自blog.csdn.net/qq_2300688967/article/details/81099234