[Android]搜索工具条 EditText

直接给效果图:

[Android]搜索工具条 EditText_第1张图片


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

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

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

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


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

[java]  view plain copy
  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.   
  10.     PackageManager pkgManager = getPackageManager();  
  11.     List<ResolveInfo> listResolveInfo = pkgManager.queryIntentActivities(intent, 0);  
  12.     if (listResolveInfo == null || listResolveInfo.size() == 0) {  
  13.         // 不支持语音识别,弹对话框提示  
  14.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  15.         builder.setTitle(R.string.speechRecognition);  
  16.         builder.setMessage(R.string.speechErrorHint);  
  17.         builder.setPositiveButton(R.string.ok, null);  
  18.         builder.create().show();  
  19.     } else {  
  20.         // 正常显示语音识别界面  
  21.         startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);  
  22.     }  
  23. }  


全部代码如下:

[java]  view plain copy
  1. package lab.sodino.searchbar;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6.   
  7. import android.app.Activity;  
  8. import android.app.ActivityManager;  
  9. import android.app.AlertDialog;  
  10. import android.app.AlertDialog.Builder;  
  11. import android.content.Context;  
  12. import android.content.DialogInterface;  
  13. import android.content.Intent;  
  14. import android.content.pm.PackageManager;  
  15. import android.content.pm.ResolveInfo;  
  16. import android.graphics.drawable.Drawable;  
  17. import android.graphics.drawable.StateListDrawable;  
  18. import android.os.Bundle;  
  19. import android.speech.RecognizerIntent;  
  20. import android.text.Editable;  
  21. import android.text.TextWatcher;  
  22. import android.util.Log;  
  23. import android.view.View;  
  24. import android.view.View.OnClickListener;  
  25. import android.widget.Button;  
  26. import android.widget.EditText;  
  27.   
  28. public class ActSearchBar extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {  
  29.     private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;  
  30.     private Button btnSpeech;  
  31.     private Button btnSearch;  
  32.     private Button btnClearEdit;  
  33.     private EditText edtSearch;  
  34.     private String[] arrSpeechKeyword;  
  35.   
  36.     /** Called when the activity is first created. */  
  37.     @Override  
  38.     public void onCreate(Bundle savedInstanceState) {  
  39.         super.onCreate(savedInstanceState);  
  40.         setContentView(R.layout.main);  
  41.         btnSpeech = (Button) findViewById(R.id.searchBtnSpeech);  
  42.         btnSpeech.setBackgroundDrawable(newSelector(this, R.drawable.search_speech, R.drawable.search_speech_pressed,  
  43.                 R.drawable.search_speech));  
  44.         btnSpeech.setOnClickListener(this);  
  45.         btnSearch = (Button) findViewById(R.id.searchButton);  
  46.         btnSearch.setOnClickListener(this);  
  47.         btnSearch.setBackgroundDrawable(newSelector(this, R.drawable.search, R.drawable.search_pressed,  
  48.                 R.drawable.search_pressed));  
  49.         btnClearEdit = (Button) findViewById(R.id.btnClearEdit);  
  50.         btnClearEdit.setOnClickListener(this);  
  51.         edtSearch = (EditText) findViewById(R.id.searchEdit);  
  52.         edtSearch.setBackgroundDrawable(newSelector(this, R.drawable.search_box, R.drawable.search_box_pressed,  
  53.                 R.drawable.search_box_pressed));  
  54.         edtSearch.setOnClickListener(this);  
  55.         edtSearch.addTextChangedListener(new TextWatcher() {  
  56.             public void onTextChanged(CharSequence s, int start, int before, int count) {  
  57.                 // Log.d("ANDROID_LAB", "OnTextChanged:" + String.valueOf(s) +  
  58.                 // " start=" + start + " before=" + before  
  59.                 // + " count=" + count);  
  60.             }  
  61.   
  62.             public void beforeTextChanged(CharSequence s, int start, int count, int after) {  
  63.                 // Log.d("ANDROID_LAB", "OnTextChanged before:" +  
  64.                 // String.valueOf(s) + " start=" + start + " count="  
  65.                 // + count + " after=" + after);  
  66.             }  
  67.   
  68.             public void afterTextChanged(Editable s) {  
  69.                 // Log.d("ANDROID_LAB", "OnTextChanged after:" +  
  70.                 // String.valueOf(s));  
  71.                 if (s == null || s.length() == 0) {  
  72.                     Log.d("ANDROID_LAB""btnClear gone");  
  73.                     btnClearEdit.setVisibility(View.GONE);  
  74.                 } else {  
  75.                     Log.d("ANDROID_LAB""btnClear visible");  
  76.                     btnClearEdit.setVisibility(View.VISIBLE);  
  77.                 }  
  78.             }  
  79.         });  
  80.     }  
  81.   
  82.     @Override  
  83.     public void onClick(View view) {  
  84.         if (view == edtSearch) {  
  85.             edtSearch.setFocusable(true);  
  86.             Log.d("ANDROID_LAB""edtSearch");  
  87.         } else if (view == btnSearch) {  
  88.   
  89.         } else if (view == btnSpeech) {  
  90.             startVoiceRecognitionActivity();  
  91.         } else if (view == btnClearEdit) {  
  92.             edtSearch.setText("");  
  93.         }  
  94.     }  
  95.   
  96.     /** 设置Selector。 */  
  97.     public static StateListDrawable newSelector(Context context, int idNormal, int idPressed, int idFocused) {  
  98.         StateListDrawable bg = new StateListDrawable();  
  99.         Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);  
  100.         Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);  
  101.         Drawable focused = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);  
  102.         // View.PRESSED_ENABLED_STATE_SET  
  103.         bg.addState(new int[] { 1684291016842919 }, pressed);  
  104.         // View.ENABLED_FOCUSED_STATE_SET  
  105.         bg.addState(new int[] { 1684290816842910 }, focused);  
  106.         // View.ENABLED_STATE_SET  
  107.         bg.addState(new int[] { 16842910 }, normal);  
  108.         // View.FOCUSED_STATE_SET  
  109.         bg.addState(new int[] { 16842908 }, focused);  
  110.         // View.EMPTY_STATE_SET  
  111.         bg.addState(new int[] {}, normal);  
  112.         return bg;  
  113.     }  
  114.   
  115.     /** 
  116.      * Fire an intent to start the speech recognition activity. 
  117.      */  
  118.     private void startVoiceRecognitionActivity() {  
  119.         Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
  120.         intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);  
  121.         // Optional text prompt to show to the user when asking them to speak  
  122.         intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");  
  123.   
  124.         PackageManager pkgManager = getPackageManager();  
  125.         List<ResolveInfo> listResolveInfo = pkgManager.queryIntentActivities(intent, 0);  
  126.         if (listResolveInfo == null || listResolveInfo.size() == 0) {  
  127.             // 不支持语音识别,弹对话框提示  
  128.             AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  129.             builder.setTitle(R.string.speechRecognition);  
  130.             builder.setMessage(R.string.speechErrorHint);  
  131.             builder.setPositiveButton(R.string.ok, null);  
  132.             builder.create().show();  
  133.         } else {  
  134.             // 正常显示语音识别界面  
  135.             startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);  
  136.         }  
  137.     }  
  138.   
  139.     /** 
  140.      * Handle the results from the recognition activity. 
  141.      */  
  142.     @Override  
  143.     protected void onActivityResult(int requestCode, int resultCode, Intent intent) {  
  144.         if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {  
  145.             // Fill the list view with the strings the recognizer thought it  
  146.             // could have heard  
  147.             ArrayList<String> arrResults = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);  
  148.             int size = arrResults.size();  
  149.             arrSpeechKeyword = new String[size];  
  150.             for (int i = 0; i < size; i++) {  
  151.                 arrSpeechKeyword[i] = arrResults.get(i);  
  152.             }  
  153.             arrResults.clear();  
  154.             arrResults = null;  
  155.             AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(R.string.searchSpeechHint);  
  156.             builder.setItems(arrSpeechKeyword, this);  
  157.             builder.create().show();  
  158.         }  
  159.   
  160.         super.onActivityResult(requestCode, resultCode, intent);  
  161.     }  
  162.   
  163.     @Override  
  164.     public void onClick(DialogInterface dialog, int which) {  
  165.         if (arrSpeechKeyword != null && arrSpeechKeyword.length > which) {  
  166.             edtSearch.setText(arrSpeechKeyword[which]);  
  167.         }  
  168.     }  
  169. }  

/res/layout/search_bar.xml

[java]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="40dip"  
  5.     android:layout_marginLeft="10dip"  
  6.     android:layout_marginRight="10dip">  
  7.     <Button android:layout_width="40dip"  
  8.         android:layout_height="wrap_content"  
  9.         android:id="@+id/searchBtnSpeech"  
  10.         android:layout_gravity="center_vertical|left"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_centerVertical="true"  
  13.         android:focusableInTouchMode="true"  
  14.         android:layout_marginRight="10dip"  
  15.     ></Button>  
  16.     <Button android:layout_width="40dip"  
  17.         android:layout_height="fill_parent"  
  18.         android:id="@+id/searchButton"  
  19.         android:textColor="#ffffffff"  
  20.         android:textSize="18sp"  
  21.         android:gravity="center"  
  22.         android:layout_marginBottom="-1dip"  
  23.         android:layout_marginTop="0dip"  
  24.         android:layout_alignParentRight="true"  
  25.         android:layout_centerVertical="true"  
  26.     ></Button>  
  27.     <EditText android:layout_width="fill_parent"  
  28.         android:layout_height="wrap_content"  
  29.         android:layout_weight="1"  
  30.         android:id="@+id/searchEdit"  
  31.         android:drawablePadding="5dip"  
  32.         android:singleLine="true"  
  33.         android:hint="@string/searchHint"  
  34.         android:textSize="16sp"  
  35.         android:layout_margin="0dip"  
  36.         android:layout_toRightOf="@id/searchBtnSpeech"  
  37.         android:layout_toLeftOf="@id/searchButton"  
  38.         android:layout_centerVertical="true"  
  39.     ></EditText>  
  40.     <Button android:layout_width="40dip"  
  41.         android:layout_height="fill_parent"  
  42.         android:id="@+id/btnClearEdit"  
  43.         android:background="@drawable/search_clean"  
  44.         android:layout_alignRight="@id/searchEdit"  
  45.         android:layout_centerVertical="true"  
  46.     ></Button>  
  47. </RelativeLayout>  
本文内容归CSDN博客博主Sodino 所有
转载请注明出处:http://blog.csdn.net/sodino/article/details/6889297
涉及到的历史帖有:[Android]代码实现StateListDrawable
http://blog.csdn.net/sodino/article/details/6797821

你可能感兴趣的:(android,layout,EditText,搜索框)