要设置EditText显示返回键或发送键,需要使用imeOptions属性。该属性定义了软键盘上的操作按钮的行为。可以在布局文件中的 EditText 标签中添加imeOptions属性,如下所示:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionSend | actionDone" />
actionSend是显示发送按钮,actionDone显示以显示返回键。同时也可以进行代码设置,具体实现方案如下:
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
/**
* 聊天界面,消息输入框键盘显示send
*/
public class MessageEditText extends AppCompatEditText {
private final String TAG = "MessageEditText";
public MessageEditText(Context context) {
super(context);
}
public MessageEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MessageEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) {
InputConnection connection = super.onCreateInputConnection(outAttrs);
// 设置SEND动作
int imeActions = outAttrs.imeOptions & EditorInfo.IME_MASK_ACTION;
if ((imeActions & EditorInfo.IME_ACTION_SEND) != 0) {
// clear the existing action
outAttrs.imeOptions ^= imeActions;
// set the send action
outAttrs.imeOptions |= EditorInfo.IME_ACTION_SEND;
}
if ((outAttrs.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
}
return connection;
}
@Override
public boolean dispatchKeyEventPreIme(@NonNull KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (listener != null) {
listener.onClickBack();
}
return true;
} else {
return super.dispatchKeyEvent(event);
}
}
public interface SoftPanelBackListener {
void onClickBack();
}
private SoftPanelBackListener listener;
public void setListener(SoftPanelBackListener listener) {
this.listener = listener;
}
}