首页 > 其他 > 详细

v7.widget.SearchView的使用

时间:2015-05-28 00:50:23      阅读:12885      评论:0      收藏:0      [点我收藏+]

SearchView出来已经相当久了,现在才拿出来讲,确实感觉有点跟不上时代的脚步,不管了,就当是给自己做个备份,忘记的时候还可以用来参考!

顺便说一下最近的糟糕情况,好像…自从…五一假期过后,就一直没好好工作,更没有好好学习,生活也没有规律,小说、游戏、熬夜…现在回想下真的很恐怖,为什么我会颓废一个月之久呢?我记得我五一假期刚回来的那个星期,我心里是铁了心要玩的,给自己的心理暗示是,从下个星期开始,要好好学习,所以我就毫无愧疚感的玩了一个星期,按理来说第二个星期开始应该会恢复过来,可是,哪有什么事都能按理来的,玩了一个星期,心玩野了,所以就这样,每天都说着,明天开始学习,一直说了一个月『明日复明日, 明日何其多? 我生待明日, 万事成蹉跎』结果这一个月中所有的事都成了蹉跎!

写这段话,没有别的目的,就是想从中吸取教训,引以为鉴!

———————以下才是正文—————————–

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

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".LauncherActivity">
      <item
          android:id="@+id/search_contact"
          android:title="搜索"
          app:showAsAction="always"   app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

这个没什么可讲的,就和其他 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;
            }
        });
    }

这里还用了另外一种方法获取 id
closeImgId = 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

<?xml version="1.0" encoding="utf-8"?>
<!--
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/search_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

    <!-- This is actually used for the badge icon *or* the badge label (or neither) -->
    <TextView
            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.support.v7.internal.widget.TintImageView
            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" />

    <LinearLayout
            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.support.v7.internal.widget.TintImageView
                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" />

        <!-- Inner layout contains the app icon, button(s) and EditText -->
        <LinearLayout
                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">

            <view class="android.support.v7.widget.SearchView$SearchAutoComplete"
                  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.support.v7.internal.widget.TintImageView
                    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" />

        </LinearLayout>

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

            <android.support.v7.internal.widget.TintImageView
                    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.support.v7.internal.widget.TintImageView
                    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" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

v7.widget.SearchView的使用

原文:http://blog.csdn.net/jxxfzgy/article/details/46055857

(0)
(3)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!