Android之搜尋方塊的純程式碼實現

來源:互聯網
上載者:User

在Android開發中,搜尋方塊是很常用的,但是控制項中沒有現成的,需要自己封裝。那要怎麼封裝呢?

方式一:使用XML和JAVA代碼相結合的方式。在XML中定義搜尋的相關控制項及布局,JAVA代碼中進行相應事件的控制。

方式二:對於浮動搜尋方塊,可以使用SearchRecentSuggestionsProvider和searchable來實現。

方式三:全部使用JAVA代碼實現。

前面兩種,網上的代碼已經很多,這裡使用方式三來實現。先來看看。


功能:<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+KDEpoaLL0cv3v/LW0NPQzOHKvqGjPC9wPgo8cD4oMimhosrkyOvE2sjduvOjrMzhyr7X1Lavx+Wz/aOsz9TKvsrkyOu1xMTayN2jrLKi1NrT0rHfz9TKvsflv9W1xM28seqhozwvcD4KPHA+KDMpoaK147v3y9HL97C0xaW686OsvavL0cv3veG5+8rks/ahozwvcD4KPHA+0sC+3dXi0Km5psTco6zO0sPHv8nS1Nf3yOfPwrfWveKhozwvcD4KPHA+KDEpoaLK5Mjrv/Khosflv9XNvLHqoaLL0cv3sLTFpdTazazSu8uuxr3P38nPo6zL+dLUv8nS1NDo0qrKudPDTGluZWFyTGF5b3V0tcTLrsa9sry+1sC0yrXP1qGjPC9wPgo8cD4oMimhosrkyOu/8r/J0tTKudPDRWRpdFRleHTKtc/WoaM8L3A+CjxwPigzKaGiyuTI67/ytcTM4cq+xNrI3cq508NFZGl0VGV4dLXEaGludMq1z9ahozwvcD4KPHA+KDQpoaLH5b/Vzbyx6r/J0tTU2kVkaXRUZXh01tC75tbG0ru49r+/09K1xM28seqjrLKiyei2qNK7tqi1xLjQ06bH+KOs0tTP7NOmx+W/1bLZ1/ehozwvcD4KPHA+KDUpoaLL0cv3sLTFpcq508NCdXR0b27M7bzTzbzGrMq1z9ajrM2syrHM7bzTteO798rCvP61xM/s06ahozwvcD4KPHA+KDYpoaLOqsHLyLexo7C0xaXN4rXEv9W85LG7yuTI67/y1bzC+qOs0OjSqsq508OxyNbYbGF5b3V0X3dlaWdodD0xwLTJ6NbDoaM8L3A+CjxwPs2ouf231r3io6y089bCv8nS1MDts/bQ6NKq08O1vbXEv9i8/rrNz+DTprXEwt+8raOsz8LD5srHyrXP1rXEtPrC66GjPC9wPgo8cD5TZWFyY2hXaWRnZXQuamF2YTxicj4KPC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">package com.example.searchframetest;import android.content.Context;import android.content.res.Resources;import android.graphics.drawable.Drawable;import android.text.Editable;import android.text.InputType;import android.text.TextUtils;import android.text.TextWatcher;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;public class SearchWidget extends LinearLayout {public final static int SEARCH_ID = 0x7ff20001;public final static String HINT_NAME = "hint";private EditText _data_editText = null;private Button _search_button = null;private Context _context = null;private Drawable _clear_drawable = null;private Drawable _search_drawable = null;private Resources _res = null;private AttributeSet _attrs = null;private String _hint = "";public SearchWidget(Context context, AttributeSet attrs) {super(context, attrs);if (context == null) {return;}_context = context;_attrs = attrs;Init();}private void Init() {InitParams();InitAttrs();InitControls();InitLayout();BindingEvents();}private void InitLayout() {this.setOrientation(LinearLayout.HORIZONTAL);}private void InitParams() {_res = _context.getResources();_clear_drawable = _res.getDrawable(R.drawable.clear);_search_drawable = _res.getDrawable(R.drawable.search);}private void InitAttrs() {for (int i = 0; i < _attrs.getAttributeCount(); i++) {if (_attrs.getAttributeName(i).equals(HINT_NAME)) {_hint = _attrs.getAttributeValue(i);break;}}}private void InitControls() {_data_editText = new EditText(_context);_search_button = new Button(_context);LayoutParams dataLayoutParams = new LayoutParams(0,LayoutParams.FILL_PARENT, 1);_data_editText.setLayoutParams(dataLayoutParams);_search_button.setCompoundDrawablesWithIntrinsicBounds(null, null,_search_drawable, null);_search_button.setId(SEARCH_ID);this.addView(_data_editText);this.addView(_search_button);// addHint();_data_editText.setHint(_hint);// _data_editText.setFocusable(false);}private void BindingEvents() {_data_editText.addTextChangedListener(_search_TextChanged);_data_editText.setOnTouchListener(_search_OnTouch);}public void setSearchOnClickListener(OnClickListener onclickListener) {_search_button.setOnClickListener(onclickListener);}public String getSearchData() {return _data_editText.getText().toString();}private TextWatcher _search_TextChanged = new TextWatcher() {@Overridepublic void afterTextChanged(Editable s) {Editable data = s;if (TextUtils.isEmpty(data)) {_data_editText.setCompoundDrawablesWithIntrinsicBounds(null,null, null, null);return;}_data_editText.setCompoundDrawablesWithIntrinsicBounds(null, null,_clear_drawable, null);}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {// Log.e("TEST","3");}};private OnTouchListener _search_OnTouch = new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_UP: {int curX = (int) event.getX();String data = _data_editText.getText().toString();if (TextUtils.isEmpty(data)) {return false;}boolean isClearPosition = (curX > v.getWidth() - 88);if (isClearPosition) {Clear(event);return true;}}default: {break;}}return false;}private void Clear(MotionEvent event) {int cacheInputType = _data_editText.getInputType();// backup// the// input// type_data_editText.setInputType(InputType.TYPE_NULL);// disable// soft// input_data_editText.onTouchEvent(event);// call native handler_data_editText.setInputType(cacheInputType);// restore input// type// addHint();_data_editText.setText("");}};}註:

(1)、給_search_button定義一個id,以便響應點擊事件。此處的SearchWidget.SEARCH_ID在實際中可能會與xml中定義的ID值有衝突,可以根據實際的情況作相應的調整。

(2)、定義HINT_NAME,以便在xml中調用搜尋方塊控制項時使用hint屬性。

(3)、InitAttrs方法中,過慮出hint屬性。

(4)、_data_editText.setHint(_hint)中設定輸入框的內容提示。

(5)、BindingEvents添加_data_editText的檔案改變和觸摸事件的監聽。

(6)、增加getSearchData函數供外部調用。

(7)、增加setSearchOnClickListener供外部設定搜尋按鈕的監聽事件。

(8)、setCompoundDrawablesWithIntrinsicBounds動態修改輸入框右側的表徵圖。

(9)、在_data_editText的layoutParams的布局參數設定中,將其寬度設定為0,高度設定為充滿父容器,比重設定為1,以確保充滿搜尋按鈕外的空間。

調用代碼:

package com.example.searchframetest;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;public class MainActivity extends Activity {private SearchWidget _search_widget = null;private TextView _result_text=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Init();}private void Init() {FetchUIControls();BindingEvents();}private void FetchUIControls() {_search_widget = (SearchWidget) findViewById(R.id.searchWidget);_result_text = (TextView) findViewById(R.id.result);}private void BindingEvents() {_search_widget.setSearchOnClickListener(_clickListener);}private OnClickListener _clickListener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case SearchWidget.SEARCH_ID: {Search();break;}default: {break;}}}};protected void Search() {String data=_search_widget.getSearchData();_result_text.setText(data);}}
註:

(1)、使用常用的擷取控制項的方式來擷取SearchWidget。

(2)、為搜尋按鈕設定監聽事件時,使用SearchWidget.SEARCH_ID來區別點擊事件的響應ID。

轉載請註明出處http://blog.csdn.net/xxdddail/article/details/23194573

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.