由效果图,搜索工具条具备的功能有:
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 speak intent.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. */ @Override public 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); } } }); } @Override public 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_SET bg.addState(new int[] { 16842910, 16842919 }, pressed); // View.ENABLED_FOCUSED_STATE_SET bg.addState(new int[] { 16842908, 16842910 }, focused); // View.ENABLED_STATE_SET bg.addState(new int[] { 16842910 }, normal); // View.FOCUSED_STATE_SET bg.addState(new int[] { 16842908 }, focused); // View.EMPTY_STATE_SET bg.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 speak intent.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. */ @Override protected 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 heard ArrayList<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); } @Override public void onClick(DialogInterface dialog, int which) { if (arrSpeechKeyword != null && arrSpeechKeyword.length > which) { edtSearch.setText(arrSpeechKeyword[which]); } } }
<?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 所有