热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Android实现搜索历史(1),android开发框架qmui

**xxx改为你想保存的sp文件名称*publicstaticSPUtilsgetInstance(Contextcontext){mContextcontext;if(

/**

  • xxx改为你想保存的sp文件名称

*/

public static SPUtils getInstance(Context context) {

mContext = context;

if (sp == null) {

sp = context.getApplicationContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);

}

return instance;

}

/**

  • 保存数据

*/

public void put(String key, Object value) {

if (value instanceof Integer) {

sp.edit().putInt(key, (Integer) value).apply();

} else if (value instanceof String) {

sp.edit().putString(key, (String) value).apply();

} else if (value instanceof Boolean) {

sp.edit().putBoolean(key, (Boolean) value).apply();

} else if (value instanceof Float) {

sp.edit().putFloat(key, (Float) value).apply();

} else if (value instanceof Long) {

sp.edit().putLong(key, (Long) value).apply();

}

}

/**

    1. 读取数据

*/

public int getInt(String key, int defValue) {

return sp.getInt(key, defValue);

}

public String getString(String key, String defValue) {

return sp.getString(key, defValue);

}

public boolean getBoolean(String key, boolean defValue) {

return sp.getBoolean(key, defValue);

}

/**

  • 读取数据

  • @param key

  • @param defValue

  • @return

*/

public T get(String key, T defValue) {

T t = null;

if (defValue instanceof String || defValue == null) {

String value = sp.getString(key, (String) defValue);

t = (T) value;

} else if (defValue instanceof Integer) {

Integer value = sp.getInt(key, (Integer) defValue);

t = (T) value;

} else if (defValue instanceof Boolean) {

Boolean value = sp.getBoolean(key, (Boolean) defValue);

t = (T) value;

} else if (defValue instanceof Float) {

Float value = sp.getFloat(key, (Float) defValue);

t = (T) value;

}

return t;

}

/**

  • 保存搜索记录

  • @param keyword

*/

public void save(String keyword) {

// 获取搜索框信息

SharedPreferences mysp = mContext.getSharedPreferences(“search_history”, 0);

String old_text = mysp.getString(“history”, “”);

// 利用StringBuilder.append新增内容,逗号便于读取内容时用逗号拆分开

StringBuilder builder = new StringBuilder(old_text);

builder.append(keyword + “,”);

// 判断搜索内容是否已经存在于历史文件,已存在则不重复添加

if (!old_text.contains(keyword + “,”)) {

SharedPreferences.Editor myeditor = mysp.edit();

myeditor.putString(“history”, builder.toString());

myeditor.commit();

}

}

public String[] getHistoryList() {

// 获取搜索记录文件内容

SharedPreferences sp = mContext.getSharedPreferences(“search_history”, 0);

String history = sp.getString(“history”, “”);

// 用逗号分割内容返回数组

String[] history_arr = history.split(",");

// 保留前50条数据

if (history_arr.length > 50) {

String[] newArrays = new String[50];

System.arraycopy(history_arr, 0, newArrays, 0, 50);

}

return history_arr;

}

/**

  • 清除搜索记录

*/

public void cleanHistory() {

SharedPreferences sp = mContext.getSharedPreferences(“search_history”, 0);

SharedPreferences.Editor editor = sp.edit();

editor.clear();

editor.commit();

}

}

4.Activity主要功能实现

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import kemizhibo.rhkj.com.ijkpalaydemo.search.KeyBoardUtils;

import kemizhibo.rhkj.com.ijkpalaydemo.search.RegularUtils;

import kemizhibo.rhkj.com.ijkpalaydemo.search.SPUtils;

public class Main2Activity extends AppCompatActivity {

ZFlowLayout historyFl;

EditText autoSearch;

Button button_search;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main2);

historyFl = findViewById(R.id.history_fl);

autoSearch=findViewById(R.id.autoSearch);

button_search=findViewById(R.id.button_search);

initHistory();

button_search.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (KeyBoardUtils.isSoftShowing(Main2Activity.this)) {

KeyBoardUtils.hintKeyboard(Main2Activity.this);

}

String searchKey = autoSearch.getText().toString();

if (!isNullorEmpty(searchKey)) {

if (RegularUtils.hasEmoji(autoSearch.getText().toString())) {

//含有非法字符串

} else {

//搜索

String keyWord = autoSearch.getText().toString();

if (!isNullorEmpty(keyWord)) {

SPUtils.getInstance(Main2Activity.this).save(autoSearch.getText().toString());

}

initHistory();

}

} else {

//搜索为空

}

}

});

}

private boolean isNullorEmpty(String str) {

return str == null || “”.equals(str);

}

/**

  • 初始化 历史记录列表

*/

private void initHistory() {

final String[] data = SPUtils.getInstance(Main2Activity.this).getHistoryList();

ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(10, 10, 10, 10);

historyFl.removeAllViews();

for (int i = 0; i

if (isNullorEmpty(data[i])) {

return;

}

//有数据往下走

final int j = i;

//添加分类块

View paramItemView = getLayoutInflater().inflate(R.layout.adapter_search_keyword, null);

TextView keyWordTv = paramItemView.findViewById(R.id.tv_content);

keyWordTv.setText(data[j]);

historyFl.addView(paramItemView, layoutParams);

keyWordTv.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (KeyBoardUtils.isSoftShowing(Main2Activity.this)) {

KeyBoardUtils.hintKeyboard(Main2Activity.this);

}

autoSearch.setText(data[j]);

autoSearch.setSelection(data[j].length());//光标在最后

if (!isNullorEmpty(data[j])) {

SPUtils.getInstance(Main2Activity.this).save(autoSearch.getText().toString());

}

//点击事件

}

});

// initautoSearch();

}

}

}

5.布局文件activity_main2.xml

android:orientation=“vertical”

xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“h
ttp://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:context=“kemizhibo.rhkj.com.ijkpalaydemo.Main2Activity”>

android:id="@+id/button_search"

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:text=“搜索”

/>

android:layout_width=“match_parent”

android:layout_height=“40dp”

android:id="@+id/autoSearch"

/>

android:id="@+id/history_fl"

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_below="@+id/title"

android:orientation=“vertical” />

adapter_search_keyword.xml

android:id="@+id/tv_content"

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_marginLeft=“15dp”

android:layout_marginTop=“12dp”

android:background="#00f"

android:paddingBottom=“8dp”

android:paddingLeft=“12dp”

android:paddingRight=“12dp”

android:includeFontPadding=“false”

android:paddingTop=“8dp”

android:textColor="#fff"

/>

ZFlowLayout.java

import android.content.Context;

import android.util.AttributeSet;

import android.view.View;

import android.view.ViewGroup;

import java.util.ArrayList;

import java.util.List;

/*****************************

  • @Copyright© 2014-2018

  • @Author:dengyalan

  • @Date:2018/1/16

  • @Description:自定义搜索标签布局

  • @Version:v1.0.0

*****************************/

public class ZFlowLayout extends ViewGroup {

/**

  • 存储所有子View

*/

private List mAllChildViews &#61; new ArrayList<>();

/**

  • 每一行的高度

*/

private List mLineHeight &#61; new ArrayList<>();

public ZFlowLayout(Context context) {

this(context, null);

}

public ZFlowLayout(Context context, AttributeSet attrs) {

this(context, attrs, 0);

}

public ZFlowLayout(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

&#64;Override

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

//父控件传进来的宽度和高度以及对应的测量模式

int sizeWidth &#61; MeasureSpec.getSize(widthMeasureSpec);

int modeWidth &#61; MeasureSpec.getMode(widthMeasureSpec);

int sizeHeight &#61; MeasureSpec.getSize(heightMeasureSpec);

int modeHeight &#61; MeasureSpec.getMode(heightMeasureSpec);

//如果当前ViewGroup的宽高为wrap_content的情况

//自己测量的宽度

int width &#61; 0;

//自己测量的高度

int height &#61; 0;

//记录每一行的宽度和高度

int lineWidth &#61; 0;

int lineHeight &#61; 0;

//获取子view的个数

int childCount &#61; getChildCount();

for (int i &#61; 0; i

View child &#61; getChildAt(i);

//测量子View的宽和高

measureChild(child, widthMeasureSpec, heightMeasureSpec);

//得到LayoutParams

MarginLayoutParams lp &#61; (MarginLayoutParams) child.getLayoutParams();

//子View占据的宽度

int childWidth &#61; child.getMeasuredWidth() &#43; lp.leftMargin &#43; lp.rightMargin;

//子View占据的高度

int childHeight &#61; child.getMeasuredHeight() &#43; lp.topMargin &#43; lp.bottomMargin;

//换行时候

if (lineWidth &#43; childWidth > sizeWidth) {

//对比得到最大的宽度
ntent的情况

//自己测量的宽度

int width &#61; 0;

//自己测量的高度

int height &#61; 0;

//记录每一行的宽度和高度

int lineWidth &#61; 0;

int lineHeight &#61; 0;

//获取子view的个数

int childCount &#61; getChildCount();

for (int i &#61; 0; i

View child &#61; getChildAt(i);

//测量子View的宽和高

measureChild(child, widthMeasureSpec, heightMeasureSpec);

//得到LayoutParams

MarginLayoutParams lp &#61; (MarginLayoutParams) child.getLayoutParams();

//子View占据的宽度

int childWidth &#61; child.getMeasuredWidth() &#43; lp.leftMargin &#43; lp.rightMargin;

//子View占据的高度

int childHeight &#61; child.getMeasuredHeight() &#43; lp.topMargin &#43; lp.bottomMargin;

//换行时候

if (lineWidth &#43; childWidth > sizeWidth) {

//对比得到最大的宽度


推荐阅读
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android源码深入理解JNI技术的概述和应用
    本文介绍了Android源码中的JNI技术,包括概述和应用。JNI是Java Native Interface的缩写,是一种技术,可以实现Java程序调用Native语言写的函数,以及Native程序调用Java层的函数。在Android平台上,JNI充当了连接Java世界和Native世界的桥梁。本文通过分析Android源码中的相关文件和位置,深入探讨了JNI技术在Android开发中的重要性和应用场景。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
author-avatar
孙俊啟66864
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有