1. 程式人生 > >android EditText 實現搜尋框點選搜尋隱藏鍵盤

android EditText 實現搜尋框點選搜尋隱藏鍵盤

佈局:

	<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);
	}
輕鬆實現搜素,並且點選隱藏鍵盤。