====================MainActivity=======================
public class MainActivity extends AppCompatActivity {
private EditText etSearch;
private TextView tvSearch;
private Button btn_delete;
private RecordSQLiteOpenHelper helper;
private SimpleCursorAdapter adapter;
private SQLiteDatabase db;
private ListView lvSearch;
private FlowLayout flowLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
etSearch = (EditText) findViewById(R.id.ed_search);
tvSearch = (TextView) findViewById(R.id.tv_search);
btn_delete = (Button) findViewById(R.id.btn_delete);
lvSearch = (ListView) findViewById(R.id.lv_search);
//初始化监听
initListener();
//初始化数据
initData();
//流式布局
initChildViews();
}
//流式布局
private void initChildViews() {
flowLayout = (FlowLayout) findViewById(R.id.flow_layout);
ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.leftMargin = 5;
lp.rightMargin = 5;
lp.topMargin = 5;
lp.bottomMargin = 5;
for(int i = 0; i < datas.length; i ++){
TextView view = new TextView(this);
view.setText(datas[i]);
view.setTextColor(Color.WHITE);
view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg));
flowLayout.addView(view,lp);
}
}
private void initListener() {
//触摸框的监听事件
etSearch.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//点击输入框显示搜索并获取焦点
etSearch.setFocusable(true);
etSearch.setFocusableInTouchMode(true);
tvSearch.setVisibility(View.VISIBLE);
return false;
}
});
tvSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
boolean hasData = hasData(etSearch.getText().toString().trim());
if (!hasData) {
insertData(etSearch.getText().toString().trim());
queryData("");
}
etSearch.setFocusable(false);
etSearch.setFocusableInTouchMode(false);
etSearch.clearFocus();
tvSearch.setVisibility(View.GONE);
//跳转到H5界面
String searchContent = etSearch.getText().toString().trim();
Toast.makeText(MainActivity.this, "搜索内容为:"+searchContent, Toast.LENGTH_SHORT).show();
etSearch.setText("");
}
});
//"清空搜索历史"按钮
btn_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//清空数据库
deleteData();
queryData("");
}
});
}
private void deleteData() {
db = helper.getWritableDatabase();
db.execSQL("delete from records");
db.close();
}
/*检查数据库中是否已经有该条记录*/
private boolean hasData(String tempName) {
//从Record这个表里找到name=tempName的id
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name =?", new String[]{tempName});
//判断是否有下一个
return cursor.moveToNext();
}
private String datas[] = {
"羊毛衫 新品","碟子","苹果8",
"髌骨带","胸罩","瑜伽球",
};
private void initData() {
//插入数据
initSearch();
//实例化数据库SQLiteOpenHelper子类对象
helper = new RecordSQLiteOpenHelper(this);
// 第一次进入时查询所有的历史记录
queryData("");
}
private void initSearch() {
for (int i = 0; i < datas.length; i++) {
final TextView textView = new TextView(this);
textView.setText(datas[i]);
//保存按下能显示selector的效果,需要设置一个如下的属性
// textView.setBackground(DrawUtils.getSelector(DrawUtils.getDrawable(MainActivity.this, Color.rgb(210, 210, 210), DensityUtil.dip2px(this, 4)), DrawUtils.getDrawable(MainActivity.this, Color.WHITE, DensityUtil.dip2px(this, 4))));
//添加点击事件,也是实现显示selector的效果的一种方式
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//跳转到H5界面
String searchContent = textView.getText().toString();
Toast.makeText(MainActivity.this, "" + searchContent, Toast.LENGTH_SHORT).show();
etSearch.setText("");
}
});
}
}
/*模糊查询数据 并显示在ListView列表上*/
private void queryData(String tempName) {
//模糊搜索
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
// 创建adapter适配器对象,装入模糊搜索的结果
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"},
new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 设置适配器
lvSearch.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/*插入数据*/
private void insertData(String tempName) {
db = helper.getWritableDatabase();
db.execSQL("insert into records(name) values('" + tempName + "')");
db.close();
}
}
======================DrawUtils============================
package com.example.lenovo.zhoukao_01;
/**
* Created by lenovo on 2017/12/4.
*/
class DrawUtils {
}
======================FlowLayout===========================
/**
* Created by lenovo on 2017/12/4.
*/
public class FlowLayout extends ViewGroup {
//存储所有子View
private List<List<View>> mAllChildViews = new ArrayList<>();
//每一行的高度
private List<Integer> mLineHeight = new ArrayList<>();
public FlowLayout(Context context) {
this(context, null);
}
public FlowLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//父控件传进来的宽度和高度以及对应的测量模式
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
//如果当前ViewGroup的宽高为wrap_content的情况
int width = 0;//自己测量的 宽度
int height = 0;//自己测量的高度
//记录每一行的宽度和高度
int lineWidth = 0;
int lineHeight = 0;
//获取子view的个数
int childCount = getChildCount();
for(int i = 0;i < childCount; i ++){
View child = getChildAt(i);
//测量子View的宽和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
//得到LayoutParams
MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();
//子View占据的宽度
int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
//子View占据的高度
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
//换行时候
if(lineWidth + childWidth > sizeWidth){
//对比得到最大的宽度
width = Math.max(width, lineWidth);
//重置lineWidth
lineWidth = childWidth;
//记录行高
height += lineHeight;
lineHeight = childHeight;
}else{//不换行情况
//叠加行宽
lineWidth += childWidth;
//得到最大行高
lineHeight = Math.max(lineHeight, childHeight);
}
//处理最后一个子View的情况
if(i == childCount -1){
width = Math.max(width, lineWidth);
height += lineHeight;
}
}
//wrap_content
setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
mAllChildViews.clear();
mLineHeight.clear();
//获取当前ViewGroup的宽度
int width = getWidth();
int lineWidth = 0;
int lineHeight = 0;
//记录当前行的view
List<View> lineViews = new ArrayList<View>();
int childCount = getChildCount();
for(int i = 0;i < childCount; i ++){
View child = getChildAt(i);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
//如果需要换行
if(childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width){
//记录LineHeight
mLineHeight.add(lineHeight);
//记录当前行的Views
mAllChildViews.add(lineViews);
//重置行的宽高
lineWidth = 0;
lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
//重置view的集合
lineViews = new ArrayList();
}
lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
lineViews.add(child);
}
//处理最后一行
mLineHeight.add(lineHeight);
mAllChildViews.add(lineViews);
//设置子View的位置
int left = 0;
int top = 0;
//获取行数
int lineCount = mAllChildViews.size();
for(int i = 0; i < lineCount; i ++){
//当前行的views和高度
lineViews = mAllChildViews.get(i);
lineHeight = mLineHeight.get(i);
for(int j = 0; j < lineViews.size(); j ++){
View child = lineViews.get(j);
//判断是否显示
if(child.getVisibility() == View.GONE){
continue;
}
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int cLeft = left + lp.leftMargin;
int cTop = top + lp.topMargin;
int cRight = cLeft + child.getMeasuredWidth();
int cBottom = cTop + child.getMeasuredHeight();
//进行子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);
}
}
================MyListView===================
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 重新计算高度
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
===================RecordSQLiteOpenHelper===================
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper{
private static String name = "temp.db";
private static Integer version = 1;
public RecordSQLiteOpenHelper(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))"); db.execSQL("insert into records(name) values('热水器')");
} @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { }}
====================drawable下的textview_bg.xml=======
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp"/>
<solid android:color="#999"/>
<size android:height="10dp" android:width="10dp"/>
</shape>
===================activity_main===================
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="92px"
android:gravity="center_vertical"
android:focusable="true"
android:padding="6px"
android:focusableInTouchMode="true"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_margin="6px"
android:layout_weight="1"
android:focusable="false"
android:focusableInTouchMode="false"
android:hint="你好啊 我来啦 别跑啊"
android:id="@+id/ed_search"
android:paddingBottom="10px"
android:paddingLeft="30px"
android:paddingTop="10px"
android:textColor="#333"
android:textColorHint="#666"
android:textSize="12sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/tv_search"
android:text="搜索"
android:layout_marginRight="20px"
android:layout_marginLeft="16px"
android:gravity="center"
android:textColor="#000fff"
android:textSize="14sp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="热搜"
android:padding="20px"
android:textSize="36px"/> <com.ljn.myapplication.FlowLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/flow_layout">
</com.ljn.myapplication.FlowLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20px">
<TextView
android:layout_width="wrap_content"
android:layout_weight="0"
android:layout_height="wrap_content"
android:text="历史搜索"
android:textSize="36px"/> <com.ljn.myapplication.MyListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv_search">
</com.ljn.myapplication.MyListView>
</LinearLayout>
<Button
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="清空历史搜索"
android:id="@+id/btn_delete"/>
</LinearLayout>
</ScrollView>