搜索


  • 搜索关键词自动完成列表,尚未完成。

activity_search.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_search"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/gray_background"
    tools:context="com.ttt.zhihudaily.activity.SearchActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar_search_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            android:id="@+id/toolbar_search"
            layout="@layout/toolbar_search" />

    </android.support.design.widget.AppBarLayout>
    <TextView
        android:id="@+id/search_fail_text"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:background="@color/gray_background"
        android:text="未搜索到结果"
        android:textSize="16sp"
        android:textColor="@color/text"/>
    <ListView
        android:id="@+id/list_view_search"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:footerDividersEnabled="false"
        android:background="@color/gray_background"/>

</LinearLayout>

toolbar_search.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    app:layout_scrollFlags="scroll|enterAlways"
    app:theme="@style/MyToolbarTheme">
    <!--app:contentInsetStart="0dp" app:contentInsetLeft="0dp" 防止内部布局左边有留白-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="5"
            android:layout_height="30dp"
            android:background="@drawable/search_selector_search"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="22dp"
                android:layout_height="22dp"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="7dp"
                android:src="@drawable/search"/>
            <EditText
                android:id="@+id/search_edit_text"
                android:layout_width="170dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="3dp"
                android:imeOptions="actionSearch"
                android:inputType="text"
                android:background="@null"
                android:hint="@string/search_hint"
                android:textColor="@color/white"
                android:textColorHint="@color/gray_pressed"
                android:maxLines="1"
                android:textSize="16sp" />
            <!--将软键盘Enter变为搜索:android:imeOptions="actionSearch" android:inputType="text"-->
            <ImageView
                android:id="@+id/search_cancel"
                android:visibility="gone"
                android:layout_width="16dp"
                android:layout_height="16dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/search_cancel"/>

        </LinearLayout>
        <ImageView
            android:id="@+id/search_start"
            android:padding="5dp"
            android:layout_marginRight="5dp"
            android:visibility="gone"
            android:layout_width="42dp"
            android:layout_height="42dp"
            android:background="@drawable/search_start_selector"
            android:src="@drawable/search"/>
    </LinearLayout>

</android.support.v7.widget.Toolbar>

serach_history_list_view_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <ImageView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="20dp"
        android:src="@drawable/search_history"/>

    <TextView
        android:id="@+id/search_history_text"
        android:layout_width="0dp"
        android:layout_weight="8"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:layout_marginLeft="5dp"
        android:textSize="15sp"
        android:layout_gravity="center_vertical"
        android:textColor="@color/gray_search_history"/>

    <ImageView
        android:id="@+id/search_history_delete"
        android:padding="6dp"
        android:layout_width="27dp"
        android:layout_height="27dp"
        android:background="@drawable/delete_search_selector"
        android:src="@drawable/search_history_delete"/>

</LinearLayout>

list_view_footer.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/footer_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/gray_shadow"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="清空搜索记录"
        android:textColor="@color/red_exit" />
</LinearLayout>

SearchActivity:

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private DBUtil mDBUtil;
    private ImageView searchCancel;
    private EditText editText;
    private ImageView searchStart;
    private MyListAdapter titleAdapter;
    private MySearchHistoryListAdapter historyAdapter;
    private ListView listView;
    private TextView textFail;
    private List<Title> titleList;
    private List<String> historyList;
    private String[] autoCompleteList = {"自", "动", "完", "成", "列", "表"};
    private Drawable divider;
    private View footerView;
    private InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        toolbar = (Toolbar) findViewById(R.id.toolbar_search);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        init();
        setEditText();

        showHistoryList();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_start:
                search();
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                break;
            case R.id.search_cancel:
                editText.setText("");
                // 重新打开软键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            default:
                break;
        }
    }

    private void init() {
        editText = (EditText) findViewById(R.id.search_edit_text);
        searchCancel = (ImageView) findViewById(R.id.search_cancel);
        searchStart = (ImageView) findViewById(R.id.search_start);
        textFail = (TextView) findViewById(R.id.search_fail_text);
        listView = (ListView) findViewById(R.id.list_view_search);

        searchCancel.setOnClickListener(this);
        searchStart.setOnClickListener(this);

        titleList = new ArrayList<>();
        historyList = new ArrayList<>();
        titleAdapter = new MyListAdapter(this, R.layout.list_view_item, titleList);
        footerView = LayoutInflater.from(this).inflate(R.layout.list_view_footer, null);
        historyAdapter = new MySearchHistoryListAdapter(this, R.layout.serach_history_list_view_item, historyList);
        // 点叉叉删除搜索记录后,重新显示列表
        historyAdapter.setDeleteHistoryListener(new MySearchHistoryListAdapter.DeleteHistoryListener() {
            @Override
            public void onDeleteFinish() {
                historyList.clear();
                historyList.addAll(mDBUtil.loadSearchHistory());
                Collections.reverse(historyList);
                if (historyList.size() == 0) {
                    listView.removeFooterView(footerView);
                }
                historyAdapter.notifyDataSetChanged();
            }
        });

        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    }

    private void setEditText() {
        // 设置按下软键盘Enter键执行搜索
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId==EditorInfo.IME_ACTION_SEARCH){
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                    search();
                }
                return true;
            }
        });

        // 监听EditText输入内容变化
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textFail.setVisibility(View.GONE);
                if (!"".equals(s.toString())) {
                    searchCancel.setVisibility(View.VISIBLE);
                    searchStart.setVisibility(View.VISIBLE);
                    showAutoCompleteList();
                } else {
                    searchCancel.setVisibility(View.GONE);
                    searchStart.setVisibility(View.GONE);
                    showHistoryList();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    // 执行搜索
    private void search() {
        String key = editText.getText().toString();
        if (!key.equals("")) {
            if (mDBUtil.isExistInSearch(key)) {
                mDBUtil.deleteSearchHistory(key);
            }
            mDBUtil.saveSearchHistory(key);
            titleList.clear();
            titleList.addAll(mDBUtil.searchNewsTitle(key));
            showTitleList();
            if (titleList.size() == 0) {
                textFail.setVisibility(View.VISIBLE);
            }
        }
    }

    // 显示搜索结果列表
    private void showTitleList() {
        listView.setDivider(null);
        if (footerView != null) {
            listView.removeFooterView(footerView);
        }
        listView.setAdapter(titleAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (HttpUtil.isNetworkConnected(SearchActivity.this)) {
                    NewsActivity.startNewsActivity(SearchActivity.this, titleAdapter.getItem(position));
                } else {
                    Snackbar.make(listView, "没有网络", Snackbar.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 显示搜索历史列表
    private void showHistoryList() {
        if (divider == null) {
            divider = listView.getDivider();
        }
        mDBUtil = DBUtil.getInstance(this);
        historyList.clear();
        historyList.addAll(mDBUtil.loadSearchHistory());
        Collections.reverse(historyList);
        listView.setDivider(divider);
        if (listView.getFooterViewsCount() == 0 && historyList.size() != 0) {
            // 增加“清除搜索记录”页脚
            listView.addFooterView(footerView, null, true);
        }
        listView.setAdapter(historyAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                // 点击最后一项清除搜索记录
                if (position == historyList.size()) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(SearchActivity.this);
                    dialog.setMessage("确定删除所有搜索记录?");
                    dialog.setCancelable(true);
                    dialog.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mDBUtil.deleteAllSearchHistory();
                            historyList.clear();
                            historyAdapter.notifyDataSetChanged();
                            listView.removeFooterView(footerView);
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.show();
                } else {
                    // 把关键词放入EditText,并执行搜索
                    editText.setText(historyAdapter.getItem(position));
                    search();
                }
            }
        });
    }

    // 显示自动完成列表
    private void showAutoCompleteList() {
        listView.setDivider(divider);
        if (footerView != null) {
            listView.removeFooterView(footerView);
        }
        listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteList));
    }

    // 触碰屏幕就关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        return super.dispatchTouchEvent(ev);
    }
}

MyListAdapter:

public class MyListAdapter extends ArrayAdapter<Title>{

    private int resource;
    private Context mContext;

    public MyListAdapter(Context context, int resource, List<Title> objects){
        super(context,resource,objects);
        this.resource=resource;
        mContext=context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View view;
        Title title = getItem(position);
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resource, null);
            viewHolder =new ViewHolder();
            viewHolder.imageView=(ImageView)view.findViewById(R.id.list_title_image);
            viewHolder.textView=(TextView)view.findViewById(R.id.list_title_text);
            view.setTag(viewHolder);
        }else {
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }
        viewHolder.textView.setText(title.getName());
        Glide.with(mContext).load(title.getImage()).placeholder(R.drawable.loading_image)
                .error(R.drawable.fail_image).into(viewHolder.imageView);
        return view;
    }

    private class ViewHolder{
        private ImageView imageView;
        private TextView textView;
    }
}

MySearchHistoryListAdapter:

public class MySearchHistoryListAdapter extends ArrayAdapter<String>{

    private int resource;
    private Context context;
    private DeleteHistoryListener listener;

    public MySearchHistoryListAdapter(Context context, int resource, List<String> objects){
        super(context,resource,objects);
        this.resource=resource;
        this.context=context;
    }

    public void setDeleteHistoryListener(DeleteHistoryListener listener){
        this.listener=listener;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View view;
        final String key = getItem(position);
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resource, null);
            viewHolder =new ViewHolder();
            viewHolder.imageView=(ImageView)view.findViewById(R.id.search_history_delete);
            viewHolder.textView=(TextView)view.findViewById(R.id.search_history_text);
            view.setTag(viewHolder);
        }else {
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }
        viewHolder.textView.setText(key);
        // 点叉叉删除对应搜索记录
        viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DBUtil.getInstance(context).deleteSearchHistory(key);
                if (listener!=null){
                    listener.onDeleteFinish();
                }
            }
        });
        return view;
    }

    private class ViewHolder{
        private ImageView imageView;
        private TextView textView;
    }

    public interface DeleteHistoryListener{
        void onDeleteFinish();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,001评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,210评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,874评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,001评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,022评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,005评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,929评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,742评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,193评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,427评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,583评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,305评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,911评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,564评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,731评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,581评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,478评论 2 352

推荐阅读更多精彩内容