EditText弹出键盘右下角是搜索按钮

默认EditText弹出键盘如下,右下角是回车按钮
在这里插入图片描述
产品设计时候UI上没有设计搜索按钮,所以需要实现键盘右下角点击搜索
在这里插入图片描述
使用EditText的两个属性

android:imeOptions="actionSearch"
android:singleLine="true"

完整代码如下:

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

    <EditText
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@android:color/darker_gray"
        android:hint="键盘无搜索"
        android:paddingLeft="20dp" />

    <EditText
        android:id="@+id/et_search"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_marginTop="30dp"
        android:background="@android:color/darker_gray"
        android:hint="键盘有搜索"
        android:imeOptions="actionSearch"
        android:paddingLeft="20dp"
        android:singleLine="true" />

</LinearLayout>

另外代码中还需要监听搜索按钮的点击,及隐藏键盘的操作


public class MainActivity extends AppCompatActivity {

    private EditText et_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_search = findViewById(R.id.et_search);

        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchContent = et_search.getText().toString().trim();
                    if (TextUtils.isEmpty(searchContent)) {
                        Toast.makeText(MainActivity.this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                    Toast.makeText(MainActivity.this, searchContent, Toast.LENGTH_SHORT).show();
                    //todo 根据内容进行查询
                    //隐藏键盘
                    KeyboardUtils.hideSoftInput(MainActivity.this);
                    return true;
                }
                return false;
            }
        });
    }
}

KeyboardUtils这里直接引用了https://github.com/Blankj/AndroidUtilCode中工具类

仅此记录

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值