适配器
public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> historys = new ArrayList<>();
public SearchHistoryAdapter(Context context, ArrayList<String> historys) {
this.context = context;
this.historys = historys;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(context).
inflate(R.layout.item_search_history, parent, false));
return holder;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.historyInfo.setText(historys.get(position));
holder.historyInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
iOnItemClickListener.onItemClick(historys.get(position));
}
});
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 删除某条回调
iOnItemClickListener.onItemDeleteClick(historys.get(position));
}
});
}
@Override
public int getItemCount() {
return historys.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView historyInfo;
ImageView delete;
public MyViewHolder(View view) {
super(view);
historyInfo = (TextView) view.findViewById(R.id.tv_item_search_history);
delete = (ImageView) view.findViewById(R.id.iv_item_search_delete);
}
}
private IOnItemClickListener iOnItemClickListener;
public void setOnItemClickListener(IOnItemClickListener iOnItemClickListener) {
this.iOnItemClickListener = iOnItemClickListener;
}
public interface IOnItemClickListener {
void onItemClick(String keyword);
void onItemDeleteClick(String keyword);
}
}
数据库
public class SearchHistoryDB extends SQLiteOpenHelper {
public static final String DB_NAME = "SearchHistory_db";
public static final String TABLE_NAME = "SearchHistory";
private static final String CREATE_TABLE = "create table if not exists " + TABLE_NAME + " ("
+ "id integer primary key autoincrement, "
+ "history text)";
public SearchHistoryDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);//创建表
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
/**
* 查询全部搜索记录
*/
public ArrayList<String> queryAllHistory() {
ArrayList<String> historys = new ArrayList<>();
//获取数据库对象
SQLiteDatabase db = getReadableDatabase();
//查询表中的数据
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, "id desc");
//获取name列的索引
for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
String history = cursor.getString(1);
historys.add(history);
}
cursor.close();//关闭结果集
db.close();//关闭数据库对象
return historys;
}
/**
* 插入数据到数据库
*/
public void insertHistory(String keyword) {
SQLiteDatabase db = getWritableDatabase();
//生成ContentValues对象
ContentValues cv = new ContentValues();
//往ContentValues对象存放数据,键-值对模式
cv.put("history", keyword);
//调用insert方法,将数据插入数据库
db.insert(TABLE_NAME, null, cv);
//关闭数据库
db.close();
}
/**
* 删除某条数据
*/
public void deleteHistory(String keyword) {
SQLiteDatabase db = getWritableDatabase();
//生成ContentValues对象
db.delete(TABLE_NAME, "history=?", new String[]{keyword});
//关闭数据库
db.close();
}
/**
* 删除全部数据
*/
public void deleteAllHistory() {
SQLiteDatabase db = getWritableDatabase();
//删除全部数据
db.execSQL("delete from " + TABLE_NAME);
//关闭数据库
db.close();
}
}
Activity
public class SearchActivity extends BaseActivity implements View.OnClickListener, SearchHistoryAdapter.IOnItemClickListener, SearchLikeAdapter.LikeClick {
private String TAG=getClass().getName();
private WakeUpScene wakeUpScene;
private ImageView imv_searching_back;
private EditText edt_inputbox;
private Button btn_sug_search;
private Drawable drawable;
private SearchHistoryDB searchHistoryDB;
//历史搜索记录
private ArrayList<String> allHistorys = new ArrayList<>();
private ArrayList<String> historys = new ArrayList<>();
private RecyclerView recyclerview_search_result;
private SearchHistoryAdapter searchHistoryAdapter;
private TextView tv_search_clean;
private InputMethodManager inputMethodManager;
private AppListBeanDao appListBeanDao;
private List<AppListBean> appListBeans;
private RecyclerView recyclerview_search_fuzzy;
private LinearLayoutManager linearLayoutManager;
private SearchLikeAdapter searchLikeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initData();
}
@SuppressLint("ClickableViewAccessibility")
private void initData() {
appListBeanDao = MyApp.appListDaoSession.getAppListBeanDao();
appListBeans = appListBeanDao.loadAll();
wakeUpScene = new WakeUpScene();
gobackHome();
drawable = getResources().getDrawable(R.mipmap.ic_emptyquery_normal);
edt_inputbox = findViewById(R.id.edt_inputbox);
btn_sug_search = findViewById(R.id.btn_sug_search);
imv_searching_back = findViewById(R.id.imv_searching_back);
tv_search_clean = findViewById(R.id.tv_search_clean);
recyclerview_search_result = findViewById(R.id.recyclerview_search_result);
recyclerview_search_fuzzy = findViewById(R.id.recyclerview_search_fuzzy);
tv_search_clean.setOnClickListener(this);
btn_sug_search.setOnClickListener(this);
imv_searching_back.setOnClickListener(this);
setDeleteDrawable();
//实例数据库
searchHistoryDB = new SearchHistoryDB(MyApp.applicationContext, SearchHistoryDB.DB_NAME, null, 1);
allHistorys=searchHistoryDB.queryAllHistory();
setAllHistorys();
//初始化历史recyclerView
recyclerview_search_result.setLayoutManager(new LinearLayoutManager(this));//list类型
searchHistoryAdapter = new SearchHistoryAdapter(this, historys);
recyclerview_search_result.setAdapter(searchHistoryAdapter);
searchHistoryAdapter.setOnItemClickListener(this);
recyclerview_search_result.setVisibility(View.VISIBLE);
if (allHistorys.size()>0)tv_search_clean.setVisibility(View.VISIBLE);
//初始化查询列表
linearLayoutManager = new LinearLayoutManager(SearchActivity.this);
recyclerview_search_fuzzy.setLayoutManager(linearLayoutManager);
searchLikeAdapter = new SearchLikeAdapter(SearchActivity.this, appListBeans);
recyclerview_search_fuzzy.setAdapter(searchLikeAdapter);
recyclerview_search_fuzzy.setVisibility(View.GONE);
searchLikeAdapter.setLikeClick(this);
edt_inputbox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
LogUtils.d(TAG, "beforeTextChanged" + " text=" + s + " count" + count);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
LogUtils.d(TAG, "onTextChanged" + " text=" + s + " count=" + count);
//todo 正在输入的时候 模糊搜索显示列表
//todo 数据的实时更新?
if (s!=null&&!s.toString().isEmpty()){
refreshQueryLikeList();
}
}
@Override
public void afterTextChanged(Editable s) {
LogUtils.d(TAG, "afterTextChanged" + " length=" + s.length());
String keyword = s.toString();
if (TextUtils.isEmpty(keyword.trim())) {
setAllHistorys();
searchHistoryAdapter.notifyDataSetChanged();
recyclerview_search_result.setVisibility(View.GONE);
recyclerview_search_fuzzy.setVisibility(View.VISIBLE);
} else {
// setKeyWordHistorys(s.toString());
}
setDeleteDrawable();
}
});
//todo
/**
* edit的触摸事件
*/
edt_inputbox.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (drawable != null && motionEvent.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) motionEvent.getRawX();
int eventY = (int) motionEvent.getRawY();
Rect rect = new Rect();
edt_inputbox.getGlobalVisibleRect(rect);//可见区域相对与屏幕来说的坐标位置.
rect.left = rect.right - drawable.getIntrinsicWidth();//getIntrinsicWidth 获取与设置相关的drawable宽度 不是图片本身宽度
if (rect.contains(eventX, eventY)) {
edt_inputbox.setText("");
//todo 刷新历史数据库
refreshHistoryList();
return true;
}
}
return false;
}
});
/**
* 软键盘操作
*/
edt_inputbox.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
/*隐藏软键盘*/
if (inputMethodManager == null) {
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
}
if (inputMethodManager != null && inputMethodManager.isActive()) {
inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
recyclerview_search_fuzzy.setVisibility(View.GONE);
addItem2HistoryList();
refreshQueryLikeList();
Toast.makeText(SearchActivity.this,"去搜索:"+edt_inputbox.getText().toString(),Toast.LENGTH_LONG).show();
return true;
}
if (keyCode == KeyEvent.KEYCODE_DEL){
String s = edt_inputbox.getText().toString();
if (TextUtils.isEmpty(s.trim())){
refreshHistoryList();
}
}
return false;
}
});
}
/**
* 刷新历史列表
*/
private void refreshHistoryList() {
ArrayList<String> strings = searchHistoryDB.queryAllHistory();
historys.clear();
historys.addAll(strings);
searchHistoryAdapter.notifyDataSetChanged();
recyclerview_search_fuzzy.setVisibility(View.GONE);
recyclerview_search_result.setVisibility(View.VISIBLE);
tv_search_clean.setVisibility(View.VISIBLE);
}
private void refreshQueryLikeList(){
String edit_result = edt_inputbox.getText().toString();
List<AppListBean> list = appListBeanDao.queryBuilder().where(AppListBeanDao.Properties.Ch_name.like("%"+edit_result+"%")).list();
if (list.size()>0){
//刷新出模糊查询的结果列表并显示
appListBeans.clear();
appListBeans.addAll(list);
searchLikeAdapter.notifyDataSetChanged();
recyclerview_search_fuzzy.setVisibility(View.VISIBLE);
recyclerview_search_result.setVisibility(View.GONE);
tv_search_clean.setVisibility(View.GONE);
//这里是不按下搜索键盘或者按钮的时候 只要查出结果就保存到历史列表
// for (AppListBean appListBean : list) {
// String ch_name = appListBean.getCh_name();
// ArrayList<String> queryAllHistory = searchHistoryDB.queryAllHistory();
// if (!queryAllHistory.contains(ch_name)){
// searchHistoryDB.insertHistory(ch_name);
// }
// }
}else{
Toast.makeText(SearchActivity.this,"没有找到匹配的小场景",Toast.LENGTH_LONG).show();
}
}
/***
*
* 添加搜索数据到历史列表
*/
private void addItem2HistoryList() {
String searWord = edt_inputbox.getText().toString();
if (!searWord.equals("")){
List<AppListBean> list = appListBeanDao.queryBuilder().where(AppListBeanDao.Properties.Ch_name.like("%"+searWord+"%")).list();
if (list.size()>0){
for (AppListBean appListBean : list) {
ArrayList<String> queryAllHistory = searchHistoryDB.queryAllHistory();
String ch_name = appListBean.getCh_name();
if (!queryAllHistory.contains(ch_name)){
searchHistoryDB.insertHistory(ch_name);
}
}
}else {
Toast.makeText(SearchActivity.this,"没有匹配的小场景",Toast.LENGTH_LONG).show();
}
}
}
/**
* 获取最新数据源
*/
private void setAllHistorys() {
historys.clear();
historys.addAll(allHistorys);
}
/**
* 注册免唤醒词
*/
private void gobackHome() {
Set<String> wakeupWord = new HashSet<>();
wakeupWord.add("返回主界面");
wakeupWord.add("返回");
wakeupWord.add("返回上层");
wakeupWord.add("退出");
HashMap<String, Set<String>> wordMap = new HashMap<>();
wordMap.put("好的",wakeupWord);
WakeUpEvent event = new WakeUpEvent(wordMap, new IWakeupCallback() {
@Override
public void onWakeup(long l, String s, String s1) {
com.tencent.wecarspeech.clientsdk.utils.log.LogUtils.d(TAG,"goback succeed");
holdTask(l);
PlayTTS(l,"已为您返回");
finish();
releaseTask(l);
// onKeyDown(KEYCODE_BACK,)
}
});
wakeUpScene.addWakeupEvent(event);
SpeechAgent.getInstance().registerWakeUpScene(wakeUpScene);
}
/**
* 在edit末端 放图片 有字显示 无字取消
*/
private void setDeleteDrawable() {
//文本框没有内容,则图片不出现
if (edt_inputbox.length() == 0) {
edt_inputbox.setCompoundDrawablesWithIntrinsicBounds(
null, null, null, null);
}
//文本框有输入内容时,文本框出现
else {
edt_inputbox.setCompoundDrawablesWithIntrinsicBounds(
null, null, drawable, null);
// mEdtInputBox.setCompoundDrawablePadding(R.dimen.dp_18);
}
}
@Override
protected void onResume() {
super.onResume();
if (wakeUpScene!=null){
SpeechAgent.getInstance().registerWakeUpScene(wakeUpScene);
}
}
@Override
protected void onPause() {
super.onPause();
if (wakeUpScene!=null){
SpeechAgent.getInstance().unregisterWakeUpScene(wakeUpScene.getSceneId());
}
}
/**
* 单条搜索记录
* @param keyword
*/
private void setKeyWordHistorys(String keyword) {
historys.clear();
for (String string : allHistorys) {
if (string.contains(keyword)) {
historys.add(string);
}
}
searchHistoryAdapter.notifyDataSetChanged();
// recyclerview_search_result.setVisibility(View.VISIBLE);
}
/**
* 点击单个搜索记录
*/
@Override
public void onItemClick(String keyword) {
// iOnSearchClickListener.OnSearchClick(keyword);
// todo 处理搜索结果
//todo 数据库 c存英文名字 或者点击edit上显示keyword 如果直接跳转界面需要DB里面存储BEAN类 包括ch_name en_name
edt_inputbox.setText(keyword);
recyclerview_search_result.setVisibility(View.GONE);
}
/**
* 删除单个搜索记录
*
*
*/
@Override
public void onItemDeleteClick(String keyword) {
searchHistoryDB.deleteHistory(keyword);
historys.remove(keyword);
searchHistoryAdapter.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imv_searching_back:
// todo
edt_inputbox.clearFocus();
hide(this);
edt_inputbox.setEnabled(false);
Intent backIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backIntent);
overridePendingTransition(0, 0);
finish();
break;
case R.id.btn_sug_search:
//todo 点击搜索 触发事件
String searWord = edt_inputbox.getText().toString();
if (TextUtils.isEmpty(searWord.trim())){
Toast.makeText(this,"请输入您想找的小程序",Toast.LENGTH_LONG).show();
}else {
// iOnSearchClickListener.OnSearchClick(searWord);
//todo 可以多加一条搜索出结果的添加数据库
hide(this);
addItem2HistoryList();
refreshQueryLikeList();
}
break;
case R.id.tv_search_clean:
searchHistoryDB.deleteAllHistory();
historys.clear();
tv_search_clean.setVisibility(View.GONE);
searchHistoryAdapter.notifyDataSetChanged();
break;
}
}
/**
* 隐藏软键盘
* @param context
*/
public void hide(Context context) {
View view = getWindow().peekDecorView();
if (view != null && view.getWindowToken() != null) {
inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 查询结果监听
* @param ch_name
* @param en_name
*/
@Override
public void LikeOnClikc(String ch_name, String en_name) {
Intent intent = new Intent(this, WebviewActivity.class);
intent.putExtra("title",ch_name);
intent.putExtra("en_name",en_name);
startActivity(intent);
}
}
layout_searching_bar
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_80"
android:layout_marginTop="@dimen/dp_72"
android:background="@color/colorActionBar"
>
<ImageView
android:id="@+id/imv_searching_back"
android:layout_width="@dimen/dp_64"
android:layout_height="@dimen/dp_64"
android:layout_marginStart="@dimen/dp_14"
android:background="@mipmap/ic_back_normal"
android:layout_centerVertical="true"
android:scaleType="fitXY" />
<EditText
android:id="@+id/edt_inputbox"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_56"
android:textSize="@dimen/sp_30"
android:hint="@string/edt_inputbox_hint"
android:paddingLeft="@dimen/dp_23"
android:paddingRight="@dimen/dp_23"
android:layout_toRightOf="@+id/imv_searching_back"
android:layout_toLeftOf="@+id/btn_sug_search"
android:layout_marginLeft="@dimen/dp_18"
android:layout_marginRight="@dimen/dp_20"
android:background="@drawable/edit_text_round"
android:textColorHint="@color/colorGray2"
android:textColor="@color/colorWhite"
android:layout_centerVertical="true"
android:imeOptions="actionSearch"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="@+id/btn_sug_search"
android:layout_width="@dimen/dp_152"
android:layout_height="@dimen/dp_56"
android:layout_marginRight="@dimen/dp_32"
android:layout_alignParentRight="true"
android:background="@drawable/button_round"
android:layout_centerVertical="true"
android:text="@string/sug_search"
android:textColor="@drawable/text_clickable_color"
android:textSize="@dimen/sp_24" />
</RelativeLayout>
activity_search
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.SearchActivity">
<include layout="@layout/layout_searching_bar"
android:id="@+id/layout_searching_bar"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_below="@id/layout_searching_bar"
android:id="@+id/recyclerview_search_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_below="@id/recyclerview_search_result"
android:id="@+id/tv_search_clean"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_corner_white"
android:gravity="center"
android:padding="10dp"
android:text="清空搜索记录"
android:textColor="@color/colorGray2"
android:textSize="14sp" />
</RelativeLayout>
item_search_history
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_item_search_history"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="@drawable/ic_history_24dp"
android:drawablePadding="16dp"
android:ellipsize="end"
android:foreground="?android:attr/selectableItemBackground"
android:gravity="center_vertical"
android:maxLines="1"
android:paddingBottom="10dp"
android:paddingLeft="16dp"
android:paddingRight="14dp"
android:paddingTop="10dp"
android:textColor="@color/text_black"
android:textSize="14sp"
tools:text="History" />
<ImageView
android:id="@+id/iv_item_search_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:background="@color/colorBG"
android:foreground="?android:attr/selectableItemBackground"
android:paddingBottom="10dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="10dp"
android:src="@drawable/ic_close_16dp" />
</LinearLayout>
text_clikable_color
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@color/colorEditTextHint"></item>
<item android:state_checked="true" android:color="@color/colorEditTextHint"></item>
<item android:state_pressed="true" android:color="@color/colorEditTextHint"></item>
<item android:color="@color/white"/>
</selector>
ic_close_16dp
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="16dp"
android:height="16dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#9DA0A3"
android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" />
</vector>
ic_history_24dp
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#9DA0A3"
android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z"/>
</vector>
网友评论