直接给效果图:

由效果图,搜索工具条具备的功能有:

1.实现语音识别,获取关键字

2.EditText有文字输入时,应在该组件末尾显示文件删除按钮,即X符号。

3.EditText与其右边的搜索按钮无缝衔接。

并不是所有的手机都支持语音识别的,所有在启动语音识别之前,应该先进行判断。综合代码如下:

 /*** Fire an intent to start the speech recognition activity.*/private void startVoiceRecognitionActivity() {Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);// Optional text prompt to show to the user when asking them to speakintent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");PackageManager pkgManager = getPackageManager();List<ResolveInfo> listResolveInfo = pkgManager.queryIntentActivities(intent, 0);if (listResolveInfo == null || listResolveInfo.size() == 0) {// 不支持语音识别,弹对话框提示AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle(R.string.speechRecognition);builder.setMessage(R.string.speechErrorHint);builder.setPositiveButton(R.string.ok, null);builder.create().show();} else {// 正常显示语音识别界面startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);}}

全部代码如下:

package lab.sodino.searchbar;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;public class ActSearchBar extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;private Button btnSpeech;private Button btnSearch;private Button btnClearEdit;private EditText edtSearch;private String[] arrSpeechKeyword;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);btnSpeech = (Button) findViewById(R.id.searchBtnSpeech);btnSpeech.setBackgroundDrawable(newSelector(this, R.drawable.search_speech, R.drawable.search_speech_pressed,R.drawable.search_speech));btnSpeech.setOnClickListener(this);btnSearch = (Button) findViewById(R.id.searchButton);btnSearch.setOnClickListener(this);btnSearch.setBackgroundDrawable(newSelector(this, R.drawable.search, R.drawable.search_pressed,R.drawable.search_pressed));btnClearEdit = (Button) findViewById(R.id.btnClearEdit);btnClearEdit.setOnClickListener(this);edtSearch = (EditText) findViewById(R.id.searchEdit);edtSearch.setBackgroundDrawable(newSelector(this, R.drawable.search_box, R.drawable.search_box_pressed,R.drawable.search_box_pressed));edtSearch.setOnClickListener(this);edtSearch.addTextChangedListener(new TextWatcher() {public void onTextChanged(CharSequence s, int start, int before, int count) {// Log.d("ANDROID_LAB", "OnTextChanged:" + String.valueOf(s) +// " start=" + start + " before=" + before// + " count=" + count);}public void beforeTextChanged(CharSequence s, int start, int count, int after) {// Log.d("ANDROID_LAB", "OnTextChanged before:" +// String.valueOf(s) + " start=" + start + " count="// + count + " after=" + after);}public void afterTextChanged(Editable s) {// Log.d("ANDROID_LAB", "OnTextChanged after:" +// String.valueOf(s));if (s == null || s.length() == 0) {Log.d("ANDROID_LAB", "btnClear gone");btnClearEdit.setVisibility(View.GONE);} else {Log.d("ANDROID_LAB", "btnClear visible");btnClearEdit.setVisibility(View.VISIBLE);}}});}@Overridepublic void onClick(View view) {if (view == edtSearch) {edtSearch.setFocusable(true);Log.d("ANDROID_LAB", "edtSearch");} else if (view == btnSearch) {} else if (view == btnSpeech) {startVoiceRecognitionActivity();} else if (view == btnClearEdit) {edtSearch.setText("");}}/** 设置Selector。 */public static StateListDrawable newSelector(Context context, int idNormal, int idPressed, int idFocused) {StateListDrawable bg = new StateListDrawable();Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);Drawable focused = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);// View.PRESSED_ENABLED_STATE_SETbg.addState(new int[] { 16842910, 16842919 }, pressed);// View.ENABLED_FOCUSED_STATE_SETbg.addState(new int[] { 16842908, 16842910 }, focused);// View.ENABLED_STATE_SETbg.addState(new int[] { 16842910 }, normal);// View.FOCUSED_STATE_SETbg.addState(new int[] { 16842908 }, focused);// View.EMPTY_STATE_SETbg.addState(new int[] {}, normal);return bg;}/*** Fire an intent to start the speech recognition activity.*/private void startVoiceRecognitionActivity() {Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);// Optional text prompt to show to the user when asking them to speakintent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");PackageManager pkgManager = getPackageManager();List<ResolveInfo> listResolveInfo = pkgManager.queryIntentActivities(intent, 0);if (listResolveInfo == null || listResolveInfo.size() == 0) {// 不支持语音识别,弹对话框提示AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setTitle(R.string.speechRecognition);builder.setMessage(R.string.speechErrorHint);builder.setPositiveButton(R.string.ok, null);builder.create().show();} else {// 正常显示语音识别界面startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);}}/*** Handle the results from the recognition activity.*/@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent intent) {if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {// Fill the list view with the strings the recognizer thought it// could have heardArrayList<String> arrResults = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);int size = arrResults.size();arrSpeechKeyword = new String[size];for (int i = 0; i < size; i++) {arrSpeechKeyword[i] = arrResults.get(i);}arrResults.clear();arrResults = null;AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.searchSpeechHint);builder.setItems(arrSpeechKeyword, this);builder.create().show();}super.onActivityResult(requestCode, resultCode, intent);}@Overridepublic void onClick(DialogInterface dialog, int which) {if (arrSpeechKeyword != null && arrSpeechKeyword.length > which) {edtSearch.setText(arrSpeechKeyword[which]);}}
}

/res/layout/search_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="40dip"android:layout_marginLeft="10dip"android:layout_marginRight="10dip"><Button android:layout_width="40dip"android:layout_height="wrap_content"android:id="@+id/searchBtnSpeech"android:layout_gravity="center_vertical|left"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:focusableInTouchMode="true"android:layout_marginRight="10dip"></Button><Button android:layout_width="40dip"android:layout_height="fill_parent"android:id="@+id/searchButton"android:textColor="#ffffffff"android:textSize="18sp"android:gravity="center"android:layout_marginBottom="-1dip"android:layout_marginTop="0dip"android:layout_alignParentRight="true"android:layout_centerVertical="true"></Button><EditText android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:id="@+id/searchEdit"android:drawablePadding="5dip"android:singleLine="true"android:hint="@string/searchHint"android:textSize="16sp"android:layout_margin="0dip"android:layout_toRightOf="@id/searchBtnSpeech"android:layout_toLeftOf="@id/searchButton"android:layout_centerVertical="true"></EditText><Button android:layout_width="40dip"android:layout_height="fill_parent"android:id="@+id/btnClearEdit"android:background="@drawable/search_clean"android:layout_alignRight="@id/searchEdit"android:layout_centerVertical="true"></Button>
</RelativeLayout>

本文内容归CSDN博客博主Sodino 所有
转载请注明出处:http://blog.csdn.net/sodino/article/details/6889297
涉及到的历史帖有:[Android]代码实现StateListDrawable
http://blog.csdn.net/sodino/article/details/6797821

[Android]搜索工具条相关推荐

  1. 个性十足的IE搜索工具条(转)

    个性十足的IE搜索工具条(转) 互联网搜索引擎是仅次于电子邮件的第二大网络应用,几乎任何上网的人或多或少的都会用到搜索引擎,因此对广大网民们来说,搜索引擎已成为他们网上冲浪不可或缺的得力助手.而做为专 ...

  2. 淘宝闪电搜索ie工具条

    淘宝搜索ie工具条安装完成后会在ie上方出现一个淘宝搜索工具条,当您看到喜爱的产品想去淘宝购买或者去淘宝上看看价格时,不用再打开淘宝网站,然后输入搜索,只要将要查的产品输入工具条,然后点击搜索即可,异 ...

  3. 教你一招:全面认识浏览器工具条

      一. 什么是工具条 工具条(英文名称为Toolbar),又名工具栏.工具条是什么?在Google的定义搜索结果中,有17种定义.根据微软的官方定义,工具条是由一组工具条按钮或其他功能控件组成的一个 ...

  4. android简单项目及代码_Android 开源项目 (AOSP) 代码搜索工具正式发布

    我们非常高兴的为各位开发者们介绍一个 Android 开源项目 (AOSP) 的代码搜索工具: https://cs.android.com Android 开源项目的代码由一系列 Git 管理的代码 ...

  5. CAD怎么去掉右上角的搜索及用户信息工具条

    CAD怎么去掉右上角的搜索及用户信息工具条 关闭CAD软件,按快捷键win+R打开运行框,输入 regedit 打开注册表 找到: 计算机\HKEY_CURRENT_USER\Software\Aut ...

  6. 文件搜索工具android,Search Everything下载

    在PC系统上,又一款很知名的本地文件搜索工具,名称叫做Everything,而在android平台上,也有一款如此功能的应用,它的名字叫 Search Everything,十分小巧,但是其功能却是十 ...

  7. 360极速浏览器终极奥义之——更改划词工具条的搜索为百度搜索

    下面这张图是在chrome.dll里提取到的十六进制码,通过十六进制转换得到相应的字符串 "https://www.so.com/s?q=%s&src=360chrome_zoned ...

  8. 360极速浏览器更改划词工具条的搜索为百度搜索

    下面这张图是在chrome.dll里提取到的十六进制码,通过十六进制转换得到相应的字符串 "https://www.so.com/s?q=%s&src=360chrome_zoned ...

  9. [Android工具]更新安卓百度云盘百度网盘资源搜索工具,安卓网盘搜索软件

        更新一个网盘搜索工具:就叫"网盘搜索",之前发的叫"village"(山寨云) 网盘搜索的搜索源: 山寨云的搜索源: 山寨云: 功能:免费好用的网盘资源 ...

最新文章

  1. AI时代的高科技读心术:算法解码脑中图像
  2. html form通过ajax提交表单提交数据,Jquery通过Ajax方式来提交Form表单的具体实现
  3. springboot 利用configureMessageConverters add FastJsonHttpMessageConverter 实现返回JSON值 null to ...
  4. [题解]第十一届北航程序设计竞赛预赛——L.偶回文串
  5. HDU_1874 畅通工程续(SPFA)
  6. linux文件夹权限问题
  7. 服务器遭受攻击后,这样排查处理不背锅!
  8. java中treemap释放_在Java中从TreeMap删除键
  9. Redis Sentinel安装与部署,实现redis的高可用
  10. android 编译c代码吗,在Android手机上编译C代码
  11. 网络安全中的恶意软件
  12. Linux下编写GT911触摸驱动
  13. 基于PS2手柄的Arduino遥控小车
  14. angular封装七牛云图片上传,解决同一页面多个上传按钮分别上传
  15. Failed to instantiate [com.XXX.entity.People]
  16. 2015广东最新DNS服务器地址
  17. 第一期:[开眼界] Android P预览版都有哪些设计新鲜事
  18. 让数据怎么发挥价值?先看看华为云数据使能的力量
  19. ubuntu 常用命令大全(转)
  20. 微软发布视频消息应用Qik:42秒录制、两周后自动消失

热门文章

  1. 欢迎观看Toni_hou的#生活5
  2. Mac打不开网页的解决方法
  3. 计算机文化基础试题集:
  4. 8 月最新编程语言排行榜
  5. 女生英文名字的义意:
  6. css选择器的优先级和权重问题
  7. [翻译] 在 Overleaf 中追踪修订
  8. 微信小程序父组件调用子组件方法
  9. C#报错:试图加载格式不正确的程序 0x8007000b
  10. 【C语言】请将560分钟换算成几小时几分钟,并输出换算结果相应的小时数与分钟数。 个人题解