1. 程式人生 > >【Android自定義View實戰】之自定義超簡單SearchView搜尋框

【Android自定義View實戰】之自定義超簡單SearchView搜尋框

package cn.bluemobi.dylan.searchview;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * Android自定義SearchView
 * Created by yuandl 
 */

public class SearchView extends LinearLayout implements TextWatcher, View.OnClickListener {
    /**
     * 輸入框
     */
    private EditText et_search;
    /**
     * 輸入框後面的那個清除按鈕
     */
    private Button bt_clear;


    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        /**載入佈局檔案*/
        LayoutInflater.from(context).inflate(R.layout.pub_searchview, this, true);
        /***找出控制元件*/
        et_search = (EditText) findViewById(R.id.et_search);
        bt_clear = (Button) findViewById(R.id.bt_clear);
        bt_clear.setVisibility(GONE);
        et_search.addTextChangedListener(this);
        bt_clear.setOnClickListener(this);
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    /****
     * 對使用者輸入文字的監聽
     *
     * @param editable
     */
    @Override
    public void afterTextChanged(Editable editable) {
        /**獲取輸入文字**/
        String input = et_search.getText().toString().trim();
        if (input.isEmpty()) {
            bt_clear.setVisibility(GONE);
        } else {
            bt_clear.setVisibility(VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        et_search.setText("");
    }
}


3.具體功能的實現