UI/控件/布局

 

原文:http://www.devdiv.com/article-2715-1.html

[Android]搜索工具条

2011-10-20 07:50|发布者: Vincent|评论: 35|原作者: Sodino         

由效果图,搜索工具条具备的功能有: 1.实现语音识别,获取关键字 2.EditText有文字输入时,应在该组件末尾显示文件删除按钮,即X符号。 3.EditText与其右边的搜索按钮无缝衔接。
<ignore_js_op>gif.gif
并不是所有的手机都支持语音识别的,所有在启动语音识别之前,应该先进行判断。综合代码如下:
  1.         /**
  2.          * Fire an intent to start the speech recognition activity.
  3.          */
  4.         private void startVoiceRecognitionActivity() {
  5.                 Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  6.                 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  7.                 // Optional text prompt to show to the user when asking them to speak
  8.                 intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
  9.                 PackageManager pkgManager = getPackageManager();
  10.                 List listResolveInfo = pkgManager.queryIntentActivities(intent, 0);
  11.                 if (listResolveInfo == null || listResolveInfo.size() == 0) {
  12.                         // 不支持语音识别,弹对话框提示
  13.                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  14.                         builder.setTitle(R.string.speechRecognition);
  15.                         builder.setMessage(R.string.speechErrorHint);
  16.                         builder.setPositiveButton(R.string.ok, null);
  17.                         builder.create().show();
  18.                 } else {
  19.                         // 正常显示语音识别界面
  20.                         startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
  21.                 }
  22.         }
复制代码
重写Activity的onActivityResult(int requestCode, int resultCode, Intent intent) {},将可以由Intent得到语音识别的过滤结果。
详细代码如下: lab.sodino.searchbar.ActSearchBar   语音识别代码参考自ApiDemo
  1. package lab.sodino.searchbar;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import android.app.Activity;
  6. import android.app.ActivityManager;
  7. import android.app.AlertDialog;
  8. import android.app.AlertDialog.Builder;
  9. import android.content.Context;
  10. import android.content.DialogInterface;
  11. import android.content.Intent;
  12. import android.content.pm.PackageManager;
  13. import android.content.pm.ResolveInfo;
  14. import android.graphics.drawable.Drawable;
  15. import android.graphics.drawable.StateListDrawable;
  16. import android.os.Bundle;
  17. import android.speech.RecognizerIntent;
  18. import android.text.Editable;
  19. import android.text.TextWatcher;
  20. import android.util.Log;
  21. import android.view.View;
  22. import android.view.View.OnClickListener;
  23. import android.widget.Button;
  24. import android.widget.EditText;
  25. public class ActSearchBar extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
  26.         private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
  27.         private Button btnSpeech;
  28.         private Button btnSearch;
  29.         private Button btnClearEdit;
  30.         private EditText edtSearch;
  31.         private String[] arrSpeechKeyword;
  32.         /** Called when the activity is first created. */
  33.         @Override
  34.         public void onCreate(Bundle savedInstanceState) {
  35.                 super.onCreate(savedInstanceState);
  36.                 setContentView(R.layout.main);
  37.                 btnSpeech = (Button) findViewById(R.id.searchBtnSpeech);
  38.                 btnSpeech.setBackgroundDrawable(newSelector(this, R.drawable.search_speech, R.drawable.search_speech_pressed,
  39.                                 R.drawable.search_speech));
  40.                 btnSpeech.setOnClickListener(this);
  41.                 btnSearch = (Button) findViewById(R.id.searchButton);
  42.                 btnSearch.setOnClickListener(this);
  43.                 btnSearch.setBackgroundDrawable(newSelector(this, R.drawable.search, R.drawable.search_pressed,
  44.                                 R.drawable.search_pressed));
  45.                 btnClearEdit = (Button) findViewById(R.id.btnClearEdit);
  46.                 btnClearEdit.setOnClickListener(this);
  47.                 edtSearch = (EditText) findViewById(R.id.searchEdit);
  48.                 edtSearch.setBackgroundDrawable(newSelector(this, R.drawable.search_box, R.drawable.search_box_pressed,
  49.                                 R.drawable.search_box_pressed));
  50.                 edtSearch.setOnClickListener(this);
  51.                 edtSearch.addTextChangedListener(new TextWatcher() {
  52.                         public void onTextChanged(CharSequence s, int start, int before, int count) {
  53.                                 // Log.d("ANDROID_LAB", "OnTextChanged:" + String.valueOf(s) +
  54.                                 // " start=" + start + " before=" + before
  55.                                 // + " count=" + count);
  56.                         }
  57.                         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  58.                                 // Log.d("ANDROID_LAB", "OnTextChanged before:" +
  59.                                 // String.valueOf(s) + " start=" + start + " count="
  60.                                 // + count + " after=" + after);
  61.                         }
  62.                         public void afterTextChanged(Editable s) {
  63.                                 // Log.d("ANDROID_LAB", "OnTextChanged after:" +
  64.                                 // String.valueOf(s));
  65.                                 if (s == null || s.length() == 0) {
  66.                                         Log.d("ANDROID_LAB", "btnClear gone");
  67.                                         btnClearEdit.setVisibility(View.GONE);
  68.                                 } else {
  69.                                         Log.d("ANDROID_LAB", "btnClear visible");
  70.                                         btnClearEdit.setVisibility(View.VISIBLE);
  71.                                 }
  72.                         }
  73.                 });
  74.         }
  75.         @Override
  76.         public void onClick(View view) {
  77.                 if (view == edtSearch) {
  78.                         edtSearch.setFocusable(true);
  79.                         Log.d("ANDROID_LAB", "edtSearch");
  80.                 } else if (view == btnSearch) {
  81.                 } else if (view == btnSpeech) {
  82.                         startVoiceRecognitionActivity();
  83.                 } else if (view == btnClearEdit) {
  84.                         edtSearch.setText("");
  85.                 }
  86.         }
  87.         /** 设置Selector。 */
  88.         public static StateListDrawable newSelector(Context context, int idNormal, int idPressed, int idFocused) {
  89.                 StateListDrawable bg = new StateListDrawable();
  90.                 Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);
  91.                 Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);
  92.                 Drawable focused = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);
  93.                 // View.PRESSED_ENABLED_STATE_SET
  94.                 bg.addState(new int[] { 16842910, 16842919 }, pressed);
  95.                 // View.ENABLED_FOCUSED_STATE_SET
  96.                 bg.addState(new int[] { 16842908, 16842910 }, focused);
  97.                 // View.ENABLED_STATE_SET
  98.                 bg.addState(new int[] { 16842910 }, normal);
  99.                 // View.FOCUSED_STATE_SET
  100.                 bg.addState(new int[] { 16842908 }, focused);
  101.                 // View.EMPTY_STATE_SET
  102.                 bg.addState(new int[] {}, normal);
  103.                 return bg;
  104.         }
  105.         /**
  106.          * Fire an intent to start the speech recognition activity.
  107.          */
  108.         private void startVoiceRecognitionActivity() {
  109.                 Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  110.                 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  111.                 // Optional text prompt to show to the user when asking them to speak
  112.                 intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
  113.                 PackageManager pkgManager = getPackageManager();
  114.                 List listResolveInfo = pkgManager.queryIntentActivities(intent, 0);
  115.                 if (listResolveInfo == null || listResolveInfo.size() == 0) {
  116.                         // 不支持语音识别,弹对话框提示
  117.                         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  118.                         builder.setTitle(R.string.speechRecognition);
  119.                         builder.setMessage(R.string.speechErrorHint);
  120.                         builder.setPositiveButton(R.string.ok, null);
  121.                         builder.create().show();
  122.                 } else {
  123.                         // 正常显示语音识别界面
  124.                         startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
  125.                 }
  126.         }
  127.         /**
  128.          * Handle the results from the recognition activity.
  129.          */
  130.         @Override
  131.         protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  132.                 if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
  133.                         // Fill the list view with the strings the recognizer thought it
  134.                         // could have heard
  135.                         ArrayList arrResults = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
  136.                         int size = arrResults.size();
  137.                         arrSpeechKeyword = new String[size];
  138.                         for (int i = 0; i < size; i++) {
  139.                                 arrSpeechKeyword[i] = arrResults.get(i);
  140.                         }
  141.                         arrResults.clear();
  142.                         arrResults = null;
  143.                         AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.searchSpeechHint);
  144.                         builder.setItems(arrSpeechKeyword, this);
  145.                         builder.create().show();
  146.                 }
  147.                 super.onActivityResult(requestCode, resultCode, intent);
  148.         }
  149.         @Override
  150.         public void onClick(DialogInterface dialog, int which) {
  151.                 if (arrSpeechKeyword != null && arrSpeechKeyword.length > which) {
  152.                         edtSearch.setText(arrSpeechKeyword[which]);
  153.                 }
  154.         }
  155. }
复制代码
/res/layout/search_bar.xml
  1.         android:layout_width="fill_parent"
  2.         android:layout_height="40dip"
  3.            android:layout_marginLeft="10dip"
  4.            android:layout_marginRight="10dip">
  5.    
  6.             android:layout_height="wrap_content"
  7.             android:id="@+id/searchBtnSpeech"
  8.             android:layout_gravity="center_vertical|left"
  9.             android:layout_alignParentLeft="true"
  10.             android:layout_centerVertical="true"
  11.             android:focusableInTouchMode="true"
  12.             android:layout_marginRight="10dip"
  13.     >
  14.        
  15.                 android:layout_height="fill_parent"
  16.                 android:id="@+id/searchButton"
  17.                 android:textColor="#ffffffff"
  18.                 android:textSize="18sp"
  19.                 android:gravity="center"
  20.                 android:layout_marginBottom="-1dip"
  21.                 android:layout_marginTop="0dip"
  22.                 android:layout_alignParentRight="true"
  23.                 android:layout_centerVertical="true"
  24.         >
  25.           
  26.                 android:layout_height="wrap_content"
  27.                 android:layout_weight="1"
  28.                 android:id="@+id/searchEdit"
  29.                 android:drawablePadding="5dip"
  30.                 android:singleLine="true"
  31.                 android:hint="@string/searchHint"
  32.                 android:textSize="16sp"
  33.                 android:layout_margin="0dip"
  34.                 android:layout_toRightOf="@id/searchBtnSpeech"
  35.                 android:layout_toLeftOf="@id/searchButton"
  36.                 android:layout_centerVertical="true"
  37.         >
  38.        
  39.                 android:layout_height="fill_parent"
  40.                 android:id="@+id/btnClearEdit"
  41.                 android:background="@drawable/search_clean"
  42.                 android:layout_alignRight="@id/searchEdit"
  43.                 android:layout_centerVertical="true"
  44.         >
复制代码
本例子对于我来说最重要的是search_bar.xml,哈哈。 涉及到的历史帖有: [Android]代码实现StateListDrawable http://www.devdiv.com/thread-92751-1-1.html
posted on 2013-01-18 15:04  zhengbeibei  阅读(927)  评论(0编辑  收藏  举报