首页 » Android » Android初学----自定义搜索框

Android初学----自定义搜索框

原文 http://blog.csdn.net/DearLC/article/details/79248047

2018-02-04 02:00:48阅读(445)

废话不多说,先上效果图吧!

<a href=Android初学----自定义搜索框" src="http://img.blog.csdn.net/20180203162708954?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRGVhckxD/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述" title="">

做APP开发,搜索框是不可缺少的,下面说一说做这个搜索框的思路吧。

首先是布局,如下:

Android初学----自定义搜索框

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    >
    <LinearLayout
        android:id="@+id/input_layout"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <FrameLayout
            android:id="@+id/edit_text_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_weight="1">
        </FrameLayout>
    </LinearLayout>
    <Button
        android:id="@+id/search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索"/>
</LinearLayout>

由于要实现点击搜索以后框内文字变成可删除的标签,EditText和标签Chip都是动态添加的,这里实现的标签效果来源于GitHub大神的Chip库 materialChipView

下面就是自定义View的内容:

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.robertlevonyan.views.chip.Chip;
import com.robertlevonyan.views.chip.OnCloseClickListener;
import com.ylc.ylcrobot.R;
import java.util.List;
/**
 * Created by AA on 2018/2/3.
 * @author wenchao
 */
public class CustomSearchView extends LinearLayout implements View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener,
        OnCloseClickListener {
    private Context context;
    private Button searchButton;
    private FrameLayout editTextLayout;
    private EditText editText;
    private ImageView resetImg;
    private LinearLayout inputLayout;
    private Chip chip;
    private List<String> searchList;
    private InputListener inputListener;
    public CustomSearchView(Context context) {
        super(context);
        initView(context);
    }
    public CustomSearchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }
    /**
     * 初始化布局
     * @param context
     */
    private void initView(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.search_layout, this);
        editTextLayout = findViewById(R.id.edit_text_layout);
        searchButton = findViewById(R.id.search_button);
        inputLayout = findViewById(R.id.input_layout);
        inputLayout.setBackgroundResource(android.R.drawable.edit_text);
        initEditText();
        initResetImg();
        editTextLayout.addView(editText);
        inputLayout.addView(resetImg);
        searchButton.setOnClickListener(this);
        editTextLayout.setOnClickListener(this);
        closeKeyBoard();
        resetImg.setVisibility(GONE);
    }
    /**
     * 初始化EditText
     */
    private void initEditText() {
        editText = new EditText(context);
        editText.setBackgroundColor(Color.TRANSPARENT);
        FrameLayout.LayoutParams editTextParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editText.setPadding(1, 1, 50, 1);
        Drawable drawable = getResources().getDrawable(android.R.drawable.ic_menu_search);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        editText.setCompoundDrawables(drawable, null, null, null);
        editText.setCompoundDrawablesRelative(drawable, null, null, null);
        editText.setCompoundDrawablePadding(8);
        editText.setLayoutParams(editTextParams);
        editText.addTextChangedListener(this);
    }
    /**
     * 初始化删除图标
     */
    private void initResetImg() {
        resetImg = new ImageView(context);
        resetImg.setImageResource(android.R.drawable.ic_delete);
        resetImg.setTag("reset");
        LinearLayout.LayoutParams resetImgParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        resetImgParams.rightMargin = 1;
        resetImgParams.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        resetImg.setLayoutParams(resetImgParams);
        resetImg.setOnClickListener(this);
    }
    /**
     * 隐藏软键盘
     */
    private void closeKeyBoard() {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //isOpen若返回true,则表示输入法打开
        boolean isOpen = imm.isActive();
        if (isOpen) {
            //隐藏软键盘 //
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
    /**
     * 监听editText输入值改变显示右侧删除图标
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        String inputText = s.toString().trim();
        if (TextUtils.isEmpty(s)) {
            resetImg.setVisibility(GONE);
//            tipsListView.setVisibility(GONE);
        } else {
            resetImg.setVisibility(VISIBLE);
            if (inputListener != null) {
                inputListener.inputChange(inputText);
            }
        }
    }
    /**
     * 处理点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        if (v.getTag() != null && v.getTag().equals("reset")) {
            closeKeyBoard();
            handleEditTextLayoutClick();
            editText.setText("");
            editText.requestFocus();
            this.chip = null;
        }
        if (v.getId() == R.id.search_button) {
            addChip();
            if (inputListener != null) {
                inputListener.startSearch(chip.getChipText());
            }
        }
        if (v.getId() == R.id.edit_text_layout) {
            handleEditTextLayoutClick();
        }
    }
    /**
     * 处理搜索框点击事件
     */
    private void handleEditTextLayoutClick() {
        View view = editTextLayout.getChildAt(0);
        if (view instanceof Chip) {
            editTextLayout.removeAllViews();
            editTextLayout.addView(editText);
            editText.setText(chip.getChipText());
            editText.setSelection(chip.getChipText().length());
            editText.requestFocus();
        }
    }
    /**
     * 添加chip
     */
    private void addChip() {
        editTextLayout.removeAllViews();
        String input_data = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input_data)) {
            return;
        }
        chip = new Chip(context);
        chip.setChipText(input_data);
        chip.setClosable(true);
        chip.setOnCloseClickListener(this);
        editTextLayout.addView(chip);
    }
    /**
     * 清空搜索框
     */
    public void setEmpty() {
        editTextLayout.removeAllViews();
        if (editText != null) {
            editText.setText("");
            editTextLayout.addView(editText);
        }
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }
    @Override
    public void onCloseClick(View v, Chip chip) {
        editTextLayout.removeAllViews();
        editTextLayout.addView(editText);
        editText.setText("");
        editText.requestFocus();
        this.chip = null;
    }
    /**
     * 设置搜索框提示内容
     * @param s
     */
    public void setTextTips(String s) {
        if (editText != null) {
            editText.setHint(s);
        }
    }
    /**
     * 输入框监听回调
     */
    public interface InputListener {
        /**
         * 输入框值改变回调方法
         *
         * @param inputText
         */
        void inputChange(String inputText);
        /**
         * 点击提示数据回调方法
         *
         * @param clickData 点击的数据
         */
        void clickTipsData(String clickData);
        /**
         * 点击搜索的回调方法
         * @param searchData 数据
         */
        void startSearch(String searchData);
    }
}

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹