android EditText 实现搜索框点击搜索隐藏键盘

本文介绍如何在Android中配置EditText,使其在点击搜索框后自动隐藏软键盘。关键在于设置XML布局文件中的属性,以实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

布局:

	<EditText
				android:id="@+id/search_input"
				android:background="#00000000"
				android:layout_width="0dp"
				android:layout_weight="1"
				android:layout_height="match_parent"
				android:layout_marginLeft="5dip"
				android:layout_marginRight="3dp"
				android:drawableLeft="@drawable/push_mail_search"
				android:drawablePadding="5dp"
				android:ellipsize="end"
				android:hint="搜索"
				android:imeOptions="actionSearch"
				android:singleLine="true"
				android:focusable="true"
				android:paddingLeft="2dp"
				android:maxLines="1"
				android:textColorHint="@color/gray_btn_bg_color"
				android:textColor="#222222"
				android:textSize="15sp" />

这是我项目里的布局文件,想要让EditText 显示搜索,最主要是两个配置:

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

点击搜索框隐藏键盘:

search_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 当按了搜索之后关闭软键盘
                    Utils.hideKeyboard(search_input);
                    return true;
                }

                return false;
            }
        });
这里用到的工具类
 Utils.hideKeyboard(search_input);

如下:

/**
	 * 隐藏软键盘
	 *
	 * @param context :上下文环境,一般为Activity实例
	 * @param view    :一般为EditText
	 */
	public static void hideKeyboard(View view) {
		InputMethodManager manager = (InputMethodManager) view.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}
轻松实现搜素,并且点击隐藏键盘。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值