android v7.widget.SearchView的使用

我们的项目中很多的搜索功能都是通过SearchView来实现的,因为这个控件给我们封装了很多功能,也正因为这个,SearchView很多样式不好控制,比如输入框的背景图片,输入框的字体颜色等等!不过如果看过源码的朋友就能轻松实现这些。ok,来看下SearchView的使用步骤1、定义 menu.xml
xmlns:app=" http://schemas.android.com/apk/res-auto"
xmlns:tools=" http://schemas.android.com/tools"
tools:context=".LauncherActivity">

android:id="@+id/search_contact"
android:title="搜索"
app:showAsAction="always" app:actionViewClass="android.support.v7.widget.SearchView"/>
这个没什么可讲的,就和其他 menu 菜单项一样,唯一不同的是加入了app:actionViewClass=”android.support.v7.widget.SearchView”2、获取 SearchView@Override

public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
final MenuItem item = menu.findItem(R.id.search_contact);
mSearchView = (SearchView) MenuItemCompat.getActionView(item);
return true;
}通过MenuItem的兼容版MenuItemCompat获取SearchView;获取了SearchView,我们就能设置其相应的属性,比如我想让它一开始就处于显示SearchView的状态mSearchView.setIconified(false);而我不想让它隐藏SearchView,则可以mSearchView.setIconifiedByDefault(false); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mSearchText = newText ;
doSearch();
return true;
}
});监听输入框变化和执行搜索操作后的回掉,所以我们可以在这里做相应的搜索功能。还有几个方法用的比较少,这里就不讲了,不过这些方法中确没有获取输入框的方法,无法获取输入框,那么我们就不能对其风格进行修改,不能改变输入框的背景,字体等等,这样看起来就和整个 app 的风格很不协调,而且每个系统显示的还不一样,这样是不应许的!3、修改 SearchView 的样式在第二点的时候,我们已经获取到了SearchView,可以通过源码找到其资源文件,然后通过 id 来获取相应的 view,比如获取输入框
mEdit = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);SearchView.SearchAutoComplete 其实就是输入框,它是继承之 EditView;最后来看一个具体实例额代码: private void setSearchView() { final float density = getResources().getDisplayMetrics().density;
mSearchView.setIconified(false);
mSearchView.setIconifiedByDefault(false);
final int closeImgId = context.getResources().getIdentifier("search_close_btn", "id", getPackageName());
ImageView closeImg = (ImageView) mSearchView.findViewById(closeImgId);
if (closeImg != null) {
LinearLayout.LayoutParams paramsImg = (LinearLayout.LayoutParams) closeImg.getLayoutParams();
paramsImg.topMargin = (int) (-2 * density);
closeImg.setImageResource(R.mipmap.clear_img);
closeImg.setLayoutParams(paramsImg);
}
final int editViewId = context.getResources().getIdentifier("search_src_text", "id", getPackageName());
mEdit = (SearchView.SearchAutoComplete) mSearchView.findViewById(editViewId);
if (mEdit != null) {
mEdit.setHintTextColor(getResources().getColor(R.color.color_hint));
mEdit.setTextColor(getResources().getColor(R.color.color_white));
mEdit.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
mEdit.setHint(String.format(getResources().getString(R.string.search_hint_tip), MemoryData.departmentList.get(mPosition).getMembers().size()));
}
LinearLayout rootView = (LinearLayout) mSearchView.findViewById(R.id.search_bar);
rootView.setBackgroundResource(R.drawable.edit_bg);
rootView.setClickable(true);
LinearLayout editLayout = (LinearLayout) mSearchView.findViewById(R.id.search_plate);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) editLayout.getLayoutParams();
LinearLayout tipLayout = (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
LinearLayout.LayoutParams tipParams = (LinearLayout.LayoutParams) tipLayout.getLayoutParams();
tipParams.leftMargin = 0;
tipParams.rightMargin = 0;
tipLayout.setLayoutParams(tipParams);
ImageView icTip = (ImageView) mSearchView.findViewById(R.id.search_mag_icon);
icTip.setImageResource(R.mipmap.ic_search_tip);
params.topMargin = (int) (4 * density);
editLayout.setLayoutParams(params);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mSearchText = newText ;
doSearch();
return true;
}
});
}这里还用了另外一种方法获取 idcloseImgId = context.getResources().getIdentifier(“search_close_btn”, “id”, getPackageName())其实直接用 R.id.search_close_btn是一样的,没有区别!总结:SearchView 的使用其实很简单,但是有的时候我们想要修改一点点样式却很难下手,这里重点就是说明如何获取每个 child view,通过 view 来改变其样式,核心代码也就是mEdit = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);最后附上资源文件abc_search_view.xml

android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">


android:id="@+id/search_badge"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:layout_marginBottom="2dip"
android:drawablePadding="0dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:attr/textColorPrimary"
android:visibility="gone" />

android:id="@+id/search_button"
style="?attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:focusable="true"
android:contentDescription="@string/abc_searchview_description_search" />

android:id="@+id/search_edit_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:layout_marginTop="4dip"
android:layout_marginBottom="4dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:orientation="horizontal"
android:layoutDirection="locale">

android:id="@+id/search_mag_icon"
android:layout_width="@dimen/abc_dropdownitem_icon_width"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:layout_gravity="center_vertical"
android:visibility="gone"
style="@style/RtlOverlay.Widget.AppCompat.SearchView.MagIcon" />


android:id="@+id/search_plate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:orientation="horizontal">

android:id="@+id/search_src_text"
android:layout_height="36dip"
android:layout_width="0dp"
android:layout_weight="1"
android:minWidth="@dimen/abc_search_view_text_min_width"
android:layout_gravity="bottom"
android:paddingLeft="@dimen/abc_dropdownitem_text_padding_left"
android:paddingRight="@dimen/abc_dropdownitem_text_padding_right"
android:singleLine="true"
android:ellipsize="end"
android:background="@null"
android:inputType="text|textAutoComplete|textNoSuggestions"
android:imeOptions="actionSearch"
android:dropDownHeight="wrap_content"
android:dropDownAnchor="@id/search_edit_frame"
android:dropDownVerticalOffset="0dip"
android:dropDownHorizontalOffset="0dip" />

android:id="@+id/search_close_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="8dip"
android:paddingRight="8dip"
android:layout_gravity="center_vertical"
android:background="?attr/selectableItemBackgroundBorderless"
android:focusable="true"
android:contentDescription="@string/abc_searchview_description_clear" />


android:id="@+id/submit_area"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent">

android:id="@+id/search_go_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:paddingLeft="16dip"
android:paddingRight="16dip"
android:background="?attr/selectableItemBackgroundBorderless"
android:visibility="gone"
android:focusable="true"
android:contentDescription="@string/abc_searchview_description_submit" />

android:id="@+id/search_voice_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:paddingLeft="16dip"
android:paddingRight="16dip"
android:background="?attr/selectableItemBackgroundBorderless"
android:visibility="gone"
android:focusable="true"
android:contentDescription="@string/abc_searchview_description_voice" />





android.support.v7.widget.SearchView开发记录

SearchView焦点问题

 mSearchView.clearFocus();

SearchView展开状态

mSearchView.setIconified(false)

SearchView获取输入框:SearchView.SearchAutoComplete

mEdit = (SearchView.SearchAutoComplete)   mSearchView.findViewById(R.id.search_src_text)

SearchView 查询图标默认位于编辑框内

    mSearchView.setIconifiedByDefault(false);

SearchView修改样式

 找到V7包下关于SearchView 资源布局文件,根据id来取得相关子View控件,然后设置子View的样式;关于设置自定义样式,主要是关于Shape,Laylist,Selector的设置
  mEdit = (SearchView.SearchAutoComplete)  mSearchView.findViewById(R.id.search_src_text);

关键代码

menu 布局文件:

 

activity 关键代码:

SearchView.SearchAutoComplete mEdit;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Log.i(TAG, "MainSearchActivity:onCreateOptionsMenu:140:" + "onCreateOptionsMenu()");
    getMenuInflater().inflate(R.menu.menu_search, menu);
    final MenuItem item = menu.findItem(R.id.action_search);
    mSearchView = (SearchView) MenuItemCompat.getActionView(item);
    mSearchView.setIconifiedByDefault(false);
    mEdit = (SearchView.SearchAutoComplete) mSearchView.findViewById(R.id.search_src_text);
    mEdit.setText(value);
    mEdit.setSelection(value.length());
    mSearchView.setQueryHint("输入您感兴趣的...");

   final LinearLayout search_edit_frame= (LinearLayout) mSearchView.findViewById(R.id.search_edit_frame);
   search_edit_frame.setBackgroundResource(R.drawable.shape_from_edit);
   search_edit_frame.setClickable(true);

    mEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            search_edit_frame.setPressed(hasFocus);
        }
    });

    mEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            search_edit_frame.setPressed(true);
        }
    });

    mEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
             /*判断是否是“GO”键*/
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                /*隐藏软键盘*/
                mSearchView.clearFocus();
                search_edit_frame.setPressed(false);
                KeyBoardUtils.closeKeybord(mEdit, ct);
                //清空
                if (!StringUtils.isEmpty(v.getText().toString())) {
                    contentlists.clear();
                    value = v.getText().toString();
                    page = 1;
                    resqustData(page);
                }
                return true;
            }
            return false;
        }
    });
    return true;
}


你可能感兴趣的:(android v7.widget.SearchView的使用)