一、概述
使用menu配合searchview可以实现常见的搜索框,详细介绍使用参考文章,我自己的项目没有采用这种方式, 使用EditText配合Button做了一个搜索的bar。实现效果如下:
二、实现
xml文件:(自定义内容和样式被移除),
主要是这两个代码实现系统输入法的搜索按钮 android:singleLine="true",android:imeOptions="actionSearch"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="60dp"
android:padding="10dp">
<EditText
android:id="@+id/search_txt"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent"
android:textSize="16dp"
android:singleLine="true"
android:imeOptions="actionSearch"
android:layout_marginRight="10dp"
/>
<Button
android:id="@+id/search_btn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textAllCaps="false"
/>
</LinearLayout>
java文件:
主要是添加监听setOnEditorActionListener,判断监听执行逻辑就行了,同时按钮也执行相同的逻辑多了一个收起系统键盘操作
public class SearchFragment extends Fragment implements AdapterView.OnItemClickListener,
View.OnClickListener, TextView.OnEditorActionListener {
//region UI变量
private EditText edit_OrderNumber;
private Button btn_Search;
//endregion
...
/**
* 初始化UI数据
*/
private void initShowUIData()
{
//待续使用
searchAdapter = new HistoryOrderAdapter(searchList, getContext());
list_search.setAdapter(searchAdapter);
list_search.setOnItemClickListener(this);
btn_Search.setOnClickListener(this);
//设置搜索事件监听
edit_OrderNumber.setOnEditorActionListener(this);
}
/**
* 搜索更新数据
*/
private void showSearchInfo(String number)
{
...
}
@Override
public void onClick(View view) {
if (view.getId()==R.id.search_btn) {
closeSoftKeybord(edit_OrderNumber,getContext());
showSearchInfo(edit_OrderNumber.getText().toString());
}
}
/**
* 监听搜索按钮
*/
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
showSearchInfo(v.getText().toString());
return true;
}
return false;
}
/**
*收起系统键盘的操作
*/
public void closeSoftKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
}
三、扩展
针对类似通讯录那种时时输入进行查找的实现,也是实现监听和上述监听有所不同,addTextChangedListener监听edittext的文本内容变化进行相关逻辑处理。
edit_OrderNumber.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d(TAG, "onTextChanged: "+charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
EditView的自定义样式:光标,下划线,选中图标,选中文字颜色 参考文章