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();
}
}