Android 实现搜索历史(2),Android开发知识点

本文详细介绍了如何在Android应用中实现搜索历史记录的保存、读取和清除功能。通过新建一个SharePreference工具类,利用StringBuilder和SharedPreferences来管理搜索记录,并在Activity中进行初始化操作,实现了自动填充和清除历史记录的功能。
摘要由CSDN通过智能技术生成

//进行子View进行布局

child.layout(cLeft, cTop, cRight, cBottom);

left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;

}

left = 0;

top += lineHeight;

}

}

/**

  • 与当前ViewGroup对应的LayoutParams

*/

@Override

public LayoutParams generateLayoutParams(AttributeSet attrs) {

return new MarginLayoutParams(getContext(), attrs);

}

}

第二步:新建一个SharePreference工具类,用来保存、读取、清除历史搜索记录,这里贴上这三个方法的代码

/**

  • 保存搜索记录

  • @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();

}

最后呢,就到了关键的一步啦,在Activity里进行读写初始化操作啦。

package cn.cnpp.searchhistory;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.text.Editable;

import android.text.TextWatcher;

import android.view.Gravity;

import android.view.View;

import a

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值